python - 列表中出现次数最多的元素

标签 python list

有没有办法将列表中最常出现的元素的列表输出到列表中,或者如果存在平局,则将所有最常出现的元素输出到列表中?

我想在不导入任何类的情况下解决这个问题!

例如,[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/

相关文章:

python - 获得 Pandas 数据框组的中位数

python - 如何在 scikit-learn CountVectorizer 中计算术语频率

python - 如果,if-else和Elif语句

java - 如何在Java中检索Array中List的第一个和第二个元素?

python - 如何从 python 中的元素列表中删除特殊字符?

python - 在 Python Jupyter Notebook 中显示所有错误输出行

python - 如何反转具有重复值的字典

python - 列表切片和复制

c# - 如何在 C# 中的 List<Tuple<string,string>> 中搜索字符串

python - 如果列表不是 None,则获取列表的第一个元素 : Python