按共同项目排序

时间:2016-02-18 08:08:17

标签: python list sorting

我需要根据项目之间的共同点对列表进行排序。例如,我有这些列表:

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在所有列表中都很常见,接下来是a或c,它们在两个列表中都很常见。

有没有更简单的方法在python中实现这一点而不是编写我自己的实现?

3 个答案:

答案 0 :(得分:4)

使用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

答案 1 :(得分:2)

from collections import Counter

a = ['a', 'b', 'f', 'd', 'c']
b = ['b', 'f', 'e', 'a']
c = ['c', 'f', 'b']

ctr = Counter(a + b + c)
common = ctr.most_common()

>>> common
[('b', 3), ('f', 3), ('a', 2), ('c', 2), ('e', 1), ('d', 1)]

common_list_vals = [t[0] for t in common]

>>> common_list_vals
['b', 'f', 'a', 'c', 'e', 'd']

>>> for my_list in [a, b, c]:
        print [val for val in common_list_vals if val in my_list]
['b', 'f', 'a', 'c', 'd']
['b', 'f', 'a', 'e']
['b', 'f', 'c']

请注意,有多个有效的'答案,例如:

['f', 'b', 'a', 'c', 'd']
['f', 'b', 'a', 'e']
['f', 'b', 'c']

['f', 'b', 'c', 'a', 'd']
['f', 'b', 'a', 'e']
['f', 'b', 'c']

答案 2 :(得分:1)

你可以这样试试,

[]

<强>输出:

>>> lst1 = ['a', 'b', 'f', 'd', 'c']
>>> lst2 = ['b', 'f', 'e', 'a']
>>> lst3 = ['c', 'f', 'b']
>>> lst = lst1 + lst2 + lst3
>>> lst1 = sorted(lst1, key=lambda x: lst.count(x), reverse=True)
>>> lst2 = sorted(lst2, key=lambda x: lst.count(x), reverse=True)
>>> lst3 = sorted(lst3, key=lambda x: lst.count(x), reverse=True)