在Python列表中计算出现次数

9

我有一个整数列表,例如:

l = [1, 2, 3, 4, 4, 4, 1, 1, 1, 2]

我正在尝试列出在l中出现次数最多的三个元素,并按频率降序排列。因此,在这种情况下,我想要列表[1,4,2],因为1l中出现最多(四次),接下来是4,有三个实例,然后是2,有两个实例。我只想要前三个结果,所以3(只有一个实例)不在列表中。
如何生成该列表?
4个回答

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中引入的。如果您使用的是旧版本,则可以使用此处的实现


哇,Python已经实现了你需要的任何功能。我只想提醒你需要一个足够新的Python版本才能运行。如果你正在运行2.6版本,那么你还没有Counter。 - Winston Ewert

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

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时要小心(即键和值被交换):这将导致值的覆盖(如果两个项目具有相同的计数,则只会将一个写回字典)。


1

不使用集合:

a = reversed(sorted(l,key=l.count))
outlist = []
for element in a:
  if element not in outlist:
    outlist.append(element)

第一行代码按计数对所有原始项进行排序。

for循环是必要的,以便在不丢失顺序的情况下去重(可能有更好的方法)。


1
key=l.count 很糟糕:这意味着您需要对整个列表进行n平方次遍历(对于每个元素计算该元素出现的次数)。更好的方法是使用 collection.Counter 或类似的解决方案,只需一次遍历即可生成计数。 - Duncan
@Duncan 确实,我没有考虑到这个复杂性!感谢你指出来。 - Eduardo Ivanec

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接