我现在需要根据项目在其中的常见程度对列表进行排序。例如我有这些列表:
s1 = [a, b, f, d, c]
s2 = [b, f, e, a]
s3 = [c, f, b]
所以,在操作之后这些将变成:
s1 = [b, f, a, c, d]
s2 = [b, f, a, e]
s3 = [b, f, c]
b 和 f 在所有列表中都是公共(public)的,那么接下来是 a 或 c,它们在两个列表中都是公共(public)的。
有没有比我自己编写实现更简单的方法在 python 中实现这一点?
请您参考如下方法:
使用 Counter 计算所有三个列表的所有列表元素,然后根据它们的计数对它们进行排序:
from collections import Counter
listCounts= Counter(s1+s2+s3)
listOflists = [s1,s2,s3]
for listi in listOflists:
sorted(listi, key=listCounts.get, reverse = True)
输出:
s1 = [b, f, a, c, d]
s2 = [b, f, a, e]
s3 = [f, b, c] # Because `b` and `f` has same count maybe they replaced in output
