簡體   English   中英

如何在列表中找到幾個最頻繁的元素

[英]How to find several most frequent elements in a list

我下面的程序確實在列表中找到了最常見的元素:

numbers = [7, 1, 7, 9, 2, 9, 7, 3, 0]
counter = []

for num in range(10):
    n = numbers.count(num)
    counter.append(n)

largest = max(counter)
print(counter.index(largest))

輸出是 7,這是正確的。

但是,如果我在列表中再添加 9 個:

numbers = [7, 1, 7, 9, 2, 9, 7, 3, 0, 9]

這意味着列表中有兩個最頻繁的元素(在這種情況下,7 和 9 在那里都出現了 3 次,如上所示),它只打印其中一個 - 在這種情況下為 7。

有什么方法可以更改我的代碼,以便輸出正確嗎?

這是一個適用於任何類型數據的解決方案,不僅適用於事先已知范圍內的正整數。

我們使用collections.Counter計數,提取最大計數,即 most_common 數的計數,然后列出具有相同計數的數字:

from collections import Counter

numbers = [7, 1, 7, 9, 2, 9, 7, 3, 0, 9]
counts = Counter(numbers)
max_count = counts.most_common(1)[0][1]
out = [value for value, count in counts.most_common() if count == max_count]
print(out)
# [7, 9]
for num in range(10):
    if counter[num] == largest:
        print(num)
from itertools import groupby

numbers = [7, 1, 7, 9, 2, 9, 7, 3, 0, 9]

counts = [(i, len(list(c))) for i,c in groupby(numbers)]    
print(counts)

由於列表counter的索引反映了一個排序值列表,一個簡單的解決方案是采用最高索引: len(counter) - 1 - counter[::-1].index(largest)

這是我的方法:

numbers = [7, 1, 7, 9, 2, 9, 7, 3, 0, 9]
counter = set([x for x in numbers if numbers.count(x) > 1])
print(max(counter))
# 9

暫無
暫無

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

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