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

相关推荐
浒畔居6 分钟前
机器学习模型部署:将模型转化为Web API
jvm·数据库·python
抠头专注python环境配置9 分钟前
基于Pytorch ResNet50 的珍稀野生动物识别系统(Python源码 + PyQt5 + 数据集)
pytorch·python
百***78759 分钟前
Kimi K2.5开源模型实战指南:核心能力拆解+一步API接入(Python版,避坑全覆盖)
python·microsoft·开源
喵手11 分钟前
Python爬虫实战:针对天文历法网站(以 TimeandDate 或类似的静态历法页为例),构建高精度二十四节气天文数据采集器(附xlsx导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集天文历法网站数据·构建二十四节气天文数据
zhaotiannuo_199834 分钟前
Python之2.7.9-3.9.1-3.14.2共存
开发语言·python
Keep_Trying_Go39 分钟前
基于GAN的文生图算法详解ControlGAN(Controllable Text-to-Image Generation)
人工智能·python·深度学习·神经网络·机器学习·生成对抗网络·文生图
LostSpeed1 小时前
openpnp - python2.7 script - 中文显示乱码,只能显示英文
python·openpnp
hhy_smile1 小时前
Class in Python
java·前端·python
whale fall1 小时前
celery -A tool.src.main worker --loglevel=info --queues=worker1_queue & 什么意思
python·学习·apache
naruto_lnq1 小时前
使用Fabric自动化你的部署流程
jvm·数据库·python