有没有办法将列表中最常出现的元素的列表输出到列表中,或者如果存在平局,则将所有最常出现的元素输出到列表中?
我想在不导入任何类的情况下解决这个问题!
例如,[5,4,3] 将输出 [5,4,3]。
或
[5,4,4,5] 将输出 [5,4]
我已经尝试过 max(set(list), key=list.count) 但对于领带并不起作用。
到目前为止我的工作:
test = ['test1', 'test2', 'test3']
dict = {}
for elements in test:
if elements in dict:
dict[elements] += 1
else:
dict[elements] = 0
dict[elements] += 1
print (dict)
最佳答案
您可以使用collections.Counter ,找到最大计数,然后保留具有最大计数的那些:
from collections import Counter
counts = Counter([5, 4, 4, 5, 3])
max_count = max(counts.values())
result = [k for k, count in counts.items() if count == max_count]
print(result)
输出
[5, 4]
您可以用简单的字典替换计数器:
data = [5, 4, 4, 5, 3]
counts = {}
for e in data:
counts[e] = counts.get(e, 0) + 1
max_count = max(counts.values())
result = [k for k, count in counts.items() if count == max_count]
print(result)
关于python - 列表中出现次数最多的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58105916/