Python collections.Counter()
Python collections Counter
2023-09-27 14:25:29 时间
1、问题
找出一个序列中出现次数最多的元素。
2、解决方案
collections.Counter
类中的 most_commom()
方法直接给出答案。
from collections import Counter
words = ['look', 'into', 'my', 'look', 'into', 'look', 'eyes']
word_counts = Counter(words)
top_three = word_counts.most_common(3) # 出现频率最高的三个单词
print(top_three)
输出:
[('look', 3), ('into', 2), ('my', 1)]
3、讨论
Counter
对象可以接受任意由可哈希(hashable
)元素构成的序列对象。
在底层实现上,一个 Counter
对象就是一个字典,将元素映射到它出现的次数上。
print(word_counts['look']) # 3
手动增加计数:
words = ['look', 'into', 'my', 'look', 'into', 'look', 'eyes']
word_counts = Counter(words)
for word in words:
word_counts[word] += 1
print(word_counts)
输出:
Counter({'look': 6, 'into': 4, 'my': 2, 'eyes': 2})
Counter
对象可以进行数学运算。
words = ['look', 'into', 'my', 'look', 'into', 'look', 'eyes']
word_counts = Counter(words)
a = word_counts + word_counts
print(a)
输出:
Counter({'look': 6, 'into': 4, 'my': 2, 'eyes': 2})
相关文章
- 朴素贝叶斯算法原理及Spark MLlib实例(Scala/Java/Python)
- 史上最易懂的Python正则表达式教程
- python中使用collections.Counter()方法进行计数
- Python函数:collections.defaultdict()
- 学习Python编程的19个资源
- python笔记——try except方法
- 第30天: Python collections 模块
- Python标准库——collections模块的Counter类
- python 生成测试报告并发送邮件
- python--logging库学习_第二波
- python @property
- Python collections模块
- python selenium鼠标键盘操作(ActionChains)
- Windows10下python-pcl的安装步骤说明,亲测ok
- 第12.6节 Python标准库其他内置模块导览
- 玩转Python之发短信
- 如何查看Python 安装位置以及已经安装的库 pip freeze
- 「python」实用的Scrapy框架安装指南,开始你的第一个专案-第2篇
- python--collections容器