【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 对象是得力的工具。比起用手写字典算法,更应该采用 CollectionCounter 类。

相关推荐
waicsdn_haha20 分钟前
Kubeflow 2025 全栈式机器学习平台部署指南(云原生+量子混合计算)
python·神经网络·云原生·开放原子·apache·量子计算·kubeflow
iracole1 小时前
深度学习训练Camp:第R5周:天气预测
人工智能·python·深度学习
梦丶晓羽3 小时前
自然语言处理:最大期望值算法
人工智能·python·自然语言处理·高斯混合模型·最大期望值算法
君科程序定做5 小时前
PDFMathTranslate安装使用
python
Linzerox6 小时前
Pycharm 取消拼写错误检查(Typo:in word xxx)
python·pycharm
千里码aicood6 小时前
[含文档+PPT+源码等]精品基于Python实现的校园小助手小程序的设计与实现
开发语言·前端·python
Icomi_7 小时前
【神经网络】0.深度学习基础:解锁深度学习,重塑未来的智能新引擎
c语言·c++·人工智能·python·深度学习·神经网络
蠟筆小新工程師7 小时前
Deepseek可以通过多种方式帮助CAD加速工作
开发语言·python·seepdeek
NoBarLing7 小时前
python将目录下的所欲md文件转化为html和pdf
python·pdf·html
岱宗夫up8 小时前
【Python】Django 中的算法应用与实现
数据库·python·opencv·django·sqlite