Python 按常用项目排序
我的情况是,我需要根据列表中某个项目的常见程度对列表进行排序。例如,我有以下列表:Python 按常用项目排序,python,list,sorting,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来实现这一点,而不是编写自己的实现?您可以这样尝试 >&g
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来实现这一点,而不是编写自己的实现?您可以这样尝试
>>> 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']
你可以这样试试
>>> 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']
请注意,有多个“有效”答案,例如:
['f', 'b', 'a', 'c', 'd']
['f', 'b', 'a', 'e']
['f', 'b', 'c']
及
请注意,有多个“有效”答案,例如:
['f', 'b', 'a', 'c', 'd']
['f', 'b', 'a', 'e']
['f', 'b', 'c']
及
使用
计数器
对所有三个列表的所有列表元素进行计数,然后根据它们的计数对它们进行排序:
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
使用
计数器
对所有三个列表的所有列表元素进行计数,然后根据它们的计数对它们进行排序:
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
同一列表中是否可能有多个项目?否,每个列表都将有唯一的项目。但是如果您的解决方案需要复制某些项目,则可以。这与
c
有关吗?它与a
一样“常见”。是的,a或c将出现在下一个列表中,以便在同一个列表中有多个项目?否,每个列表将有唯一的项目。但是如果您的解决方案需要复制某些项目,这是可以的c
?它与a
一样“常见”。是的,接下来是a或ckey=lambda x:listsconts[x]
也可以被key=listCounts.get
替换key=lambda x:listsconts[x]
也可以被key=listCounts.get
替换。