我的程序在下面的程序中找到了列表中最常见的元素:
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都被发现三次,如上所述),它只打印其中的一个-在本例中为7。
有没有办法改变我的代码,使输出正确?
发布于 2019-12-02 02:28:55
这里有一个解决方案,适用于任何类型的数据,而不仅仅是预先知道的范围内的正整数。
我们使用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]
发布于 2019-12-02 02:35:45
for num in range(10):
if counter[num] == largest:
print(num)
发布于 2019-12-02 02:20:44
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)
https://stackoverflow.com/questions/59128512
复制相似问题