序列中出现次数最多的元素(众数)

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})

 

posted @   花桥  阅读(53)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示