2017-02-19 101 views
2

我有一個列表,諸如這樣的:Pythonic找到頻率最高的元素?

lst = [1, 3, 5, 1, 5, 6, 1, 1, 3, 4, 5, 2, 3, 4, 5, 3, 4] 

我想找到發生最頻繁的所有的元素。 所以想:

most = [1, 3, 5] 

1,圖3和5將發生最大,這是4倍。什麼是快速,pythonic的方式來做到這一點?我試過這裏顯示的方法:

How to find most common elements of a list?

但它只給我前3名,我需要所有元素。謝謝。

+0

,在鏈接回答做了切片'popular_words [:3 ]'只返回前3名。實際計數器包含所有總數,而不僅僅是前3名。 – krock

回答

7

隨着collections.Counter列表理解

from collections import Counter 

lst = [1, 3, 5, 1, 5, 6, 1, 1, 3, 4, 5, 2, 3, 4, 5, 3, 4] 
r = [x for x, _ in Counter(lst).most_common(3)] 
print(r) 
# [1, 3, 5] 

您可以通過使用計數器值max概括爲最高的計數值:

c = Counter(lst) 
m = max(c.values()) 
r = [k for k in c if c[k] == m] 
print(r) 
# [1, 3, 5] 

對於大型iterables,有效地迭代通過計數器並停止一次所需的物品後,您可以使用與most_common而不帶任何參數:

from itertools import takewhile 

c = Counter(lst) 
m = max(c.values()) 
r = [x for x, _ in takewhile(lambda x: x[1]==m, c.most_common())] 
print(r) 
# [1, 3, 5] 

你獲得通過不通過櫃檯對象中的所有項目進行迭代,雖然有一定的開銷不必使用most_common排序的項目;所以我肯定這個絕對是畢竟是高效的。你可以用timeit做一些實驗。

+0

這是作品,但我想找到所有**元素出現頻率最高,而不僅僅是前3個。謝謝你。 –

+0

@ArjunVasudevan我已更新爲一般情況 –

0

你可以做以下的,如果你想打印所有最常見的,

from collections import Counter 
    words=[1, 3, 5, 1, 5, 6, 1, 1, 3, 4, 5, 2, 3, 4, 5, 3, 4] 
    most= [word for word, word_count in Counter(words).most_common()] 
    print (most) 
>>> 
[1, 3, 5, 4, 2, 6] 

請注意,如果你想限制,你可以進入裏面most_common()功能的數量。例如:...most_common(3)]。希望這回答你的問題。

1

您也可以用groupbyitertools模塊和list comprehension以這種方式得到相同的結果:

from itertools import groupby 

a = [1, 3, 5, 1, 5, 6, 1, 1, 3, 4, 5, 2, 3, 4, 5, 3, 4] 
most_common = 3 
final = [k for k,v in groupby(sorted(a), lambda x: x) if len(list(v)) > most_common] 

輸出:

print(final) 
>>> [1, 3, 5] 
+1

那麼,這假設您已經有一個先驗閾值 –

+0

是的。這是真的。但它可以擴展到處理所有情況。 –

相關問題