序列中出现次数最多的元素(众数)
1. collections.Counter类可以找出次数出现最多的元素,most_common方法直接给出了答案
from collections import Counter 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' ] most_words = Counter(words) print(most_words) #Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, 'not': 1, "don't": 1, "you're": 1, 'under': 1})
top_three = most_words.most_common(3)#找出出现次数前三的单词 print(top_three) #[('eyes', 8), ('the', 5), ('look', 4)]
- 在底层实现上,Counter对象是一个字典,可以打印出元素出现次数
print(most_words['eyes']) #8
- 手动增加计数
morewords = ['why','are','you','not','looking','in','my','eyes','eyes'] for word in morewords: most_words[word]+=1 print(most_words['eyes']) #3
- 还可以使用update()的方法
most_words.update(morewords) print(most_words) #Counter({'eyes': 17, 'my': 8, 'not': 6, 'the': 5, 'why': 5, 'are': 5, 'you': 5, 'looking': 5, 'in': 5, 'look': 4, 'into': 3, 'around': 2, "don't": 1, "you're": 1, 'under': 1})
2.Counter可以很容易的跟数学运算操作相结合
a = Counter(words) b = Counter(morewords) print(a+b) #Counter({'look': 4,'into': 3,'my': 4,'eyes': 10,'the': 5,'not': 2,'around': 2,"don't": 1,"you're": 1,'under': 1,'why': 1,'are': 1,'you': 1,'looking': 1,'in': 1})
微笑向暖安之若素,你若盛开清风自来
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?