我不知道我的问题是否重复,因为我找不到真正的答案。我想在换行上打印最常用的单词或数字。但是,如果频率相同,则打印两个单词/数字。
Input: green green green orange orange yellow
Output: green
Input: green green green orange orange orange yellow
Output: green
orange
Input: 1 1 2 2 3 3 4
Output: 1
2
3
Input: 1 1 1 2 2 3 3
Output: 1
答案 0 :(得分:2)
你能告诉你你尝试过什么吗?遵循代码段可能会对您有所帮助
words = ['green', 'green','green', 'yellow']
from collections import Counter
counts = Counter(words)
top = [k for k, _ in counts.most_common(list(counts.values()).count(max(counts.values())))]
print(top)
答案 1 :(得分:0)
您还可以对key
argument进行max
,然后列表推导将所有具有该计数的内容都包含在内,因为max
仅需一个:
>>> words = ['green', 'green','green', 'yellow','orange','orange','orange']
>>> list(set([i for i in words if words.count(i) == words.count(max(words,key=words.count))]))
['green', 'orange']
>>>