按常用项排序

2024-04-26 10:16:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在的情况是,我需要根据列表中某个项目的常见程度对列表进行排序。例如,我有以下列表:

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来实现这一点,而不是编写自己的实现?你知道吗


Tags: 项目方法列表s3排序情况手术s2
3条回答

你可以这样试试

>>> 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)

输出:

['b', 'f', 'a', 'c', 'd']
['b', 'f', 'a', 'e']
['f', 'b', 'c']
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']

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

相关问题 更多 >