使用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)一行代码完成统计的任务

欢迎大家讨论交流~


相关推荐
敲敲敲-敲代码19 分钟前
【PyCharm- Python- ArcGIS】:安装一个和 ArcGIS 不冲突的独立 Python让PyCharm 使用 (解决全过程记录)
python·arcgis·pycharm
猿榜编程37 分钟前
python基础-requests结合AI实现自动化数据抓取
开发语言·python·自动化
一键三联啊42 分钟前
【FastJSON】的parse与parseObject
linux·前端·python
shimly1234562 小时前
(done) 吴恩达版提示词工程 8. 聊天机器人 (聊天格式设计,上下文内容,点餐机器人)
人工智能·python·机器人
站大爷IP2 小时前
基于PySide6的聚合翻译软件设计与实现
python
灏瀚星空2 小时前
从基础到实战的量化交易全流程学习:1.2 金融市场基础
笔记·python·信息可视化·系统架构·开源
用户27784491049933 小时前
Python打造Excel记账模板,摸鱼时间也能轻松理财
人工智能·python
闲人编程3 小时前
OpenCV图像矩与形状匹配完全指南
python·opencv·图像识别
一个天蝎座 白勺 程序猿3 小时前
Python爬虫(8)Python数据存储实战:JSON文件读写与复杂结构化数据处理指南
爬虫·python·json
q_q王4 小时前
dify对接飞书云文档,并且将图片传入飞书文档
python·大模型·飞书·dify·智能体·图片展示