-4

我不知道我的问题是否重复,因为我真的找不到正确的答案。我想在新行上打印最常用的单词或数字。但是,如果频率相同,则打印两个单词/数字。

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
4

2 回答 2

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)
于 2018-10-04T05:06:57.997 回答
0

You could also do max with key argument, then list comprehension takes all that has the count of that, because max just takes one:

>>> 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']
>>> 
于 2018-10-04T05:35:03.710 回答