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

相关推荐
小小爬虾18 分钟前
关于datetime获取时间的问题
python
蓝婷儿1 小时前
6个月Python学习计划 Day 16 - 面向对象编程(OOP)基础
开发语言·python·学习
chao_7892 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
大霞上仙3 小时前
nonlocal 与global关键字
开发语言·python
Mark_Aussie3 小时前
Flask-SQLAlchemy使用小结
python·flask
程序员阿龙3 小时前
【精选】计算机毕业设计Python Flask海口天气数据分析可视化系统 气象数据采集处理 天气趋势图表展示 数据可视化平台源码+论文+PPT+讲解
python·flask·课程设计·数据可视化系统·天气数据分析·海口气象数据·pandas 数据处理
ZHOU_WUYI3 小时前
Flask与Celery 项目应用(shared_task使用)
后端·python·flask
且慢.5894 小时前
Python_day47
python·深度学习·计算机视觉
佩奇的技术笔记4 小时前
Python入门手册:异常处理
python
大写-凌祁4 小时前
论文阅读:HySCDG生成式数据处理流程
论文阅读·人工智能·笔记·python·机器学习