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

欢迎大家讨论交流~


相关推荐
Flittly几秒前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(9)Agent Teams (智能体团队)
python·agent
DevnullCoffe16 分钟前
Open Claw × 跨境电商:5个最有价值的 AI Agent 应用场景深度拆解
python·api
zh路西法30 分钟前
【宇树机器人强化学习】(六):TensorBoard图表与手柄遥控go2测试
python·深度学习·机器学习·机器人
szcsun532 分钟前
关于在pycharm中新建项目创建虚拟化环境venv
ide·python·pycharm
码路飞33 分钟前
体验完阿里「悟空」之后,我花 2 小时用 Python 撸了个 AI Agent 🔥
python·aigc
万里沧海寄云帆43 分钟前
pytorch+cpu版本对Intel Ultra 9 275HX性能的影响
人工智能·pytorch·python
java资料站1 小时前
python爬虫入门
python
1941s1 小时前
Google Agent Development Kit (ADK) 指南 第二章:环境搭建与快速开始
人工智能·python·adk·google agent
天下无贼1 小时前
【Python】2026版——FastAPI 框架快速搭建后端服务
后端·python·aigc
小蚂蚁i1 小时前
LangChain 完全学习手册:看完就能上手
后端·python·ai编程