前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python学习记录12-序列中出现次数最多的元素

Python学习记录12-序列中出现次数最多的元素

作者头像
huolong
发布2023-10-23 09:43:05
1200
发布2023-10-23 09:43:05
举报
文章被收录于专栏:技术指北技术指北

本节的内容是获取一个序列中出现次数最多的元素,这个问题应该经常见,甚至有的面试题里也会考。 我们直接开始。有个列表list1,我们要从中获取出现次数最多的word。

代码语言:javascript
复制
list1 = [
    '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'
]

tmp = dict()
for word in list1:
    if word in tmp.keys():
        tmp[word] +=1
    else: tmp[word] = 1
maxValue = max(tmp.values()) #8
result = [k for k,v in tmp.items() if v==maxValue]
print(result) #['eyes']

如果我们自己实现,那么需要借助字典的特性,将word和对应的次数形成键值对。最后再从字典里获取最大的value(即出现次数最多的),再通过获取对应的key来实现,听着就有点走弯路的样子。

在Python里,我们就可以使用collections.Counter类来处理这种场景。可以使用它的most_common来帮我们实现,也就是说我们可以这样来写。

代码语言:javascript
复制
word_counts = Counter(list1)
top_three = word_counts.most_common(3)
print(top_three)  #[('eyes', 8), ('the', 5), ('look', 4)]
#top_three 即返回前3,和后面most_common参数一致即可。
#本质上word_counts就是一个字典

print(word_counts['under'])  #1
print(word_counts['eyes'])#8
print(word_counts['my'])   #3

Counter 实例一个鲜为人知的特性是它们可以很容易的跟数学运算操作相结合

代码语言:javascript
复制
list1=['hh','aa','cc','aa','aa']
list2=['hh','hh','hh','aa','aa']
a = Counter(list1)
b = Counter(list2)
print(a)  #Counter({'aa': 3, 'hh': 1, 'cc': 1})
print(b)   #Counter({'hh': 3, 'aa': 2})
print(a+b)  #Counter({'aa': 5, 'hh': 4, 'cc': 1})
print(a-b)  #Counter({'aa': 1, 'cc': 1})

所以,以后再遇到类似的场景时候,就可以使用Counter啦。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023年10月20日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档