【发布时间】:2011-05-18 14:29:13
【问题描述】:
我有一个整数列表;例如:
l = [1, 2, 3, 4, 4, 4, 1, 1, 1, 2]
我正在尝试按频率降序列出l 中出现次数最多的三个元素。所以在这种情况下,我想要列表[1, 4, 2],因为1 在l 中出现最多(四次),4 紧随其后,有三个实例,然后2 有两个。我只想要前三个结果,所以3(只有一个实例)没有进入列表。
如何生成该列表?
【问题讨论】:
标签: python
我有一个整数列表;例如:
l = [1, 2, 3, 4, 4, 4, 1, 1, 1, 2]
我正在尝试按频率降序列出l 中出现次数最多的三个元素。所以在这种情况下,我想要列表[1, 4, 2],因为1 在l 中出现最多(四次),4 紧随其后,有三个实例,然后2 有两个。我只想要前三个结果,所以3(只有一个实例)没有进入列表。
如何生成该列表?
【问题讨论】:
标签: python
import collections
l= [1 ,2 ,3 ,4,4,4 , 1 ,1 ,1 ,2]
x=collections.Counter(l)
print(x.most_common())
# [(1, 4), (4, 3), (2, 2), (3, 1)]
print([elt for elt,count in x.most_common(3)])
# [1, 4, 2]
collections.Counter 是在 Python 2.7 中引入的。如果您使用的是旧版本,则可以使用the implementation here。
【讨论】:
l_items = set(l) # produce the items without duplicates
l_counts = [ (l.count(x), x) for x in set(l)]
# for every item create a tuple with the number of times the item appears and
# the item itself
l_counts.sort(reverse=True)
# sort the list of items, reversing is so that big items are first
l_result = [ y for x,y in l_counts ]
# get rid of the counts leaving just the items
【讨论】:
from collections import defaultdict
l= [1 ,2 ,3 ,4,4,4 , 1 , 1 ,1 ,2]
counter=defaultdict(int)
for item in l:
counter[item]+=1
inverted_dict = dict([[v,k] for k,v in counter.items()])
for count in sorted(inverted_dict.keys()):
print inverted_dict[count],count
这应该打印出“l”中最常见的项目:您需要限制为前三个。使用inverted_dict时要小心(即键和值被交换):这将导致值被覆盖(如果两个项目具有相同的计数,那么只有一个项目将被写回字典)。
【讨论】:
不使用集合:
a = reversed(sorted(l,key=l.count))
outlist = []
for element in a:
if element not in outlist:
outlist.append(element)
第一行为您提供按计数排序的所有原始项目。
for 循环是唯一化而不丢失顺序所必需的(可能有更好的方法)。
【讨论】:
key=l.count 很讨厌:这意味着您在整个列表中进行 n 平方传递(对于每个元素,计算该元素的出现次数)。最好使用 collection.Counter 之一或使用单遍生成计数的类似解决方案。