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

相关推荐
wxin_VXbishe17 分钟前
springboot合肥师范学院实习实训管理系统-计算机毕业设计源码31290
java·spring boot·python·spring·servlet·django·php
ITenderL23 分钟前
Python学习笔记-函数
python·学习笔记
zmjia11125 分钟前
全流程Python编程、机器学习与深度学习实践技术应用
python·深度学习·机器学习
_.Switch1 小时前
Python机器学习:自然语言处理、计算机视觉与强化学习
python·机器学习·计算机视觉·自然语言处理·架构·tensorflow·scikit-learn
JUNAI_Strive_ving1 小时前
番茄小说逆向爬取
javascript·python
彤银浦1 小时前
python学习记录7
python·学习
简单.is.good2 小时前
【测试】接口测试与接口自动化
开发语言·python
Envyᥫᩣ2 小时前
Python中的自然语言处理:从基础到高级
python·自然语言处理·easyui
哪 吒2 小时前
华为OD机试 - 几何平均值最大子数(Python/JS/C/C++ 2024 E卷 200分)
javascript·python·华为od
我是陈泽2 小时前
一行 Python 代码能实现什么丧心病狂的功能?圣诞树源代码
开发语言·python·程序员·编程·python教程·python学习·python教学