簡體   English   中英

計算Python列表中的出現次數

[英]Counting occurrences in a Python list

我有一個整數列表; 例如:

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

我試圖按照頻率的降序列出具有最高出現次數的l中的三個元素。 因此,在這種情況下,我想要列表[1, 4, 2] ,因為1發生在l (四次)中最多, 4表示下三個實例,然后2兩個。 我只想要前三個結果,所以3 (只有一個實例)不會列出。

我該如何生成該列表?

使用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中引入的。 如果您使用的是舊版本,則可以在此處使用此實現

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時要小心(即鍵和值被交換):這將導致值的重寫(如果兩個項具有相同的計數,則只有一個將被寫回到dict)。

不使用集合:

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

第一行為您提供按計數排序的所有原始項目。

for循環對於在不丟失順序的情況下進行統一是必要的(可能有更好的方法)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM