【Python Cookbook】S1E10 找出序列中出现次数最多的元素

目录

问题

如果我们有一个元素序列,我们想知道序列中出现次数最多的元素是什么?

解决方案

请使用 collections 模块中的 Counter 类!

python 复制代码
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'
]

from collections import Counter

word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)

在 Counter 类中,有函数 most_common(n) 方法,可以直接告诉我们 top(n) 个出现次数最多的元素以及其具体出现的次数:

讨论

当然,除了 top(n),Counter() 类有很多其他方法:

  1. 所有元素出现的次数:
python 复制代码
print(word_counts.most_common())
  1. 获取指定元素出现的次数:
python 复制代码
print(word_counts['eyes'])
  1. 手动增加次数:

方法一:循环写入:

python 复制代码
more_words = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes']

for word in more_words:
    word_counts[word] += 1
print(word_counts)

方法二:使用 update() 方法:

python 复制代码
more_words = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes']

word_counts.update(more_words)
print(word_counts)

可以说,当你面对很多需要对数据制表或者计数的问题的时候,Counter 对象是得力的工具。比起用手写字典算法,更应该采用 Collection 中 Counter 类。

相关推荐
Smoothcloud润云5 小时前
PyTorch大模型权重加载与启动耗时优化实战:定位磁盘、内存与显存瓶颈
人工智能·pytorch·python·深度学习·gpu算力
databook5 小时前
从循环到向量化:NumPy提速的7个关键思维
python·数据分析·numpy
棉猴6 小时前
玩游戏学Python1-Python和pgzero库的安装
python·pygame·玩游戏·pgzero·pgzrun
诺伦6 小时前
GEO优化数据实证:78%引用流向官网的机制拆解与小品牌三步管线实战教程 | RiseClaw玄策
python·seo·geo·内容营销·ai搜索
oooost6 小时前
pytorch学习笔记1
python·学习方法
数字融合7 小时前
透明化视频孪生虚实映射一体化融合技术
人工智能·python·数码相机
jack186897 小时前
Lovable.Dev 全栈应用快速落地实战指南
python
华研前沿标杆游学7 小时前
【标杆研学】走进茅台集团|对标学习长期主义与匠心精神
python
GitFun8 小时前
KDJ vs RSI:11年数据实测,金叉死叉输了48个点
python·股票·量化交易
李可以量化8 小时前
从零读懂配对交易(上):从套利本源到配对交易的核心逻辑
python·区块链·量化交易·通达信·qmt