【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 类。

相关推荐
别让别人觉得你做不到21 分钟前
Python(1) 做一个随机数的游戏
python
小彭律师2 小时前
人脸识别门禁系统技术文档
python
张小九993 小时前
PyTorch的dataloader制作自定义数据集
人工智能·pytorch·python
zstar-_3 小时前
FreeTex v0.2.0:功能升级/支持Mac
人工智能·python·macos·llm
苏生要努力4 小时前
第九届御网杯网络安全大赛初赛WP
linux·python·网络安全
于壮士hoho4 小时前
DeepSeek | AI需求分析
人工智能·python·ai·需求分析·dash
蒙奇D索大4 小时前
【人工智能】自然语言编程革命:腾讯云CodeBuddy实战5步搭建客户管理系统,效率飙升90%
人工智能·python·django·云计算·腾讯云
AndrewHZ4 小时前
【Python生活】如何构建一个跌倒检测的算法?
python·算法·生活·可视化分析·陀螺仪·加速度计·跌倒检测
lizz6664 小时前
Python查询ES错误ApiError(406, ‘Content-Type ...is not supported
python·elasticsearch
lqjun08274 小时前
Focal Loss 原理详解及 PyTorch 代码实现
人工智能·pytorch·python