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

相关推荐
Wpa.wk3 分钟前
自动化测试环境配置-java+python
java·开发语言·python·测试工具·自动化
带刺的坐椅11 分钟前
AI 应用工作流:LangGraph 和 Solon AI Flow,我该选谁?
java·python·ai·solon·flow·langgraph
工业互联网专业1 小时前
图片推荐系统_django+spider
python·django·毕业设计·源码·课程设计·spider·图片推荐系统
Lwcah1 小时前
Python | LGBM+SHAP可解释性分析回归预测及可视化算法
python·算法·回归
@一辈子爱你1 小时前
归来九十余日:在时代的夹缝中,与你共筑一道光
python
HsuHeinrich1 小时前
利用面积图探索历史温度的变化趋势
python·数据可视化
winfredzhang2 小时前
Python实战:手把手教你写一个带界面的“照片按日期归档与清理”工具
python·复制·日期·回收站·媒体文件备份
程序员三藏4 小时前
Jmeter自动化测试
自动化测试·软件测试·python·测试工具·jmeter·测试用例·接口测试
吴佳浩6 小时前
Langchain 浅出
python·langchain·llm
smj2302_796826526 小时前
解决leetcode第3753题范围内总波动值II
python·算法·leetcode