Python检测列表中出现次数最多的N个项目

2022-05-03 00:00:00 项目 检测 次数最多
"""
皮蛋编程(https://www.pidancode.com)
创建日期:2022/4/27
功能描述:Python检测列表中出现次数最多的N个项目
"""
words = [
   'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
   'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
   'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
   'my', 'eyes', "you're", 'under', 'pidancode', 'freepythoncode',
]

from collections import Counter
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
# outputs [('eyes', 8), ('the', 5), ('look', 4)]

# 添加更多的单词

morewords = ['why','are','you','not','looking','in','my','eyes']
word_counts.update(morewords)
print(word_counts.most_common(3))

输出:

[('eyes', 8), ('the', 5), ('look', 4)]
[('eyes', 9), ('the', 5), ('look', 4)]

相关文章