使用collection.Counter实现统计简化

背景介绍

在python的应用场景中,我们常常需要通过建立统计表来对某一个数据集中某些数据出现次数的统计,这时候经常会使用到python的字典数据类型建立映射表,一般的方法可能会比较繁琐,本篇博客介绍collection.Counter方法帮助简化统计出现数量的过程

任务设计

统计字符串'fbhsiagfhiwagbourahlbgojlrghboajwbhifalbg'中每个字母出现的次数

直接统计

python 复制代码
str_to_counts = 'fbhsiagfhiwagbourahlbgojlrghboajwbhifalbg'
str_count_dict = {}
for count in str_to_counts:
    if count in str_count_dict.keys():
        str_count_dict[count]+=1
    else:
        str_count_dict[count] = 1
print(str_count_dict)

结果

python 复制代码
{'f': 3, 'b': 6, 'h': 5, 's': 1, 'i': 3, 'a': 5, 'g': 5, 'w': 2, 'o': 3, 'u': 1, 'r': 2, 'l': 3, 'j': 2}

可以看到完成了统计的任务,但是代码不够简洁美观

使用defaultdict

python 复制代码
from collections import defaultdict
str_to_counts = 'fbhsiagfhiwagbourahlbgojlrghboajwbhifalbg'
str_count_dict = defaultdict(int)
for count in str_to_counts:
    str_count_dict[count] += 1
print(str_count_dict)

这里通过str_count_dict = defaultdict(int)默认了字典的值的类型为int,所以后面的循环中可以直接对字典的值进行+=1的操作,完成统计的任务

上面的方法看上去已经简化了,我们还可以使用collection.Counter进一步简化

python 复制代码
import collections
str_to_counts = 'fbhsiagfhiwagbourahlbgojlrghboajwbhifalbg'
str_count_dict = collections.Counter(str_to_counts)
print(str_count_dict)

可以直接通过str_count_dict = collections.Counter(str_to_counts)一行代码完成统计的任务

欢迎大家讨论交流~


相关推荐
Hacker_Oldv10 分钟前
Python技能进阶:探索Selenium库,实现网页自动化测试与爬虫
自动化测试·软件测试·爬虫·python·selenium·职场和发展
天天爱吃肉821841 分钟前
电机控制技术深度解析:从基础原理到前沿实战
python·嵌入式硬件·汽车
银河邮差2 小时前
python实战-用海外代理IP抓LinkedIn热门岗位数据
后端·python
第二只羽毛2 小时前
遵守robots协议的友好爬虫
大数据·爬虫·python·算法·网络爬虫
好难取啊2 小时前
[python学习]案例01:随机验证码与账号密码修改
python
秋邱2 小时前
价值升维!公益赋能 + 绿色技术 + 终身学习,构建可持续教育 AI 生态
网络·数据库·人工智能·redis·python·学习·docker
2501_941144423 小时前
Python + C++ 异构微服务设计与优化
c++·python·微服务
ChoSeitaku3 小时前
线代强化NO19|矩阵的相似与相似对角化
python·线性代数·矩阵
sniper_fandc4 小时前
Coze智能体实现人生模拟器
python·ai·agent·coze
white-persist4 小时前
【攻防世界】reverse | Reversing-x64Elf-100 详细题解 WP
c语言·开发语言·网络·python·学习·安全·php