我不知道我的问题是否重复,因为我真的找不到正确的答案。我想在新行上打印最常用的单词或数字。但是,如果频率相同,则打印两个单词/数字。Input: green green green orange orange yellowOutput: greenInput: green green green orange orange orange yellowOutput: green orangeInput: 1 1 2 2 3 3 4Output: 1 2 3Input: 1 1 1 2 2 3 3Output: 1
2 回答
青春有我
TA贡献1784条经验 获得超8个赞
你能说出你尝试过什么吗?跟随片段可能会对你有所帮助
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)
慕工程0101907
TA贡献1887条经验 获得超5个赞
你也可以max用keyargument,然后列表推导采用所有有计数的,因为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']
>>>
添加回答
举报
0/150
提交
取消