统计Python列表中的出现次数
我有一个整数的列表,比如说:
l = [1, 2, 3, 4, 4, 4, 1, 1, 1, 2]
我想要找出这个列表中出现次数最多的三个元素,并按照出现次数从高到低的顺序排列。所以在这个例子中,我想要的列表是 [1, 4, 2]
,因为 1
在列表中出现了最多次(四次),接下来是 4
(出现了三次),然后是 2
(出现了两次)。我只想要出现次数最多的前三个结果,所以 3
(只出现了一次)就不在这个列表里。
那我该怎么生成这个列表呢?
4 个回答
2
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的时候要小心(因为它会把键和值互换):这样会导致值被覆盖(如果两个项目的出现次数相同,那么只有一个会被写回字典中)。
8
这段代码的意思是……
首先,它定义了一个变量,这个变量用来存储一些信息。接下来,它会执行一些操作,比如计算、判断或者循环。最后,代码会输出结果,告诉我们计算的结果是什么。
如果你对代码中的某些部分不太明白,可以把它们想象成一个个小工具,每个工具都有自己的功能,组合在一起就能完成一个大任务。
总之,这段代码的目的是为了实现某个特定的功能,通过一系列的步骤来达到最终的结果。
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
19
可以使用一个叫做 collections.Counter 的工具:
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 版本中引入的。如果你用的是更老的版本,可以参考 这里的实现。