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

欢迎大家讨论交流~


相关推荐
迷藏4947 分钟前
**雾计算中的边缘智能:基于Python的轻量级任务调度系统设计与实现**在物联网(IoT)飞速发展的今天,传统云
java·开发语言·python·物联网
biubiubiu070612 分钟前
从 Python 和 Node.js 的流行看 Java 的真实位置
java·python·node.js
大江东去浪淘尽千古风流人物16 分钟前
【Basalt】Basalt void SqrtKeypointVioEstimator<Scalar_>::optimize() VIO优化流程
数据库·人工智能·python·机器学习·oracle
CoberOJ_44 分钟前
(2026-04-01更新)小白自己写,量化回测系统stock-quant(六)
python·ai·股票·量化·交易·回测·a股港股美股
qq_283720051 小时前
Python:time/datetime 模块教程
python·时间·模块·日期
qq_252614411 小时前
PyMySQL 对 caching_sha2_password 支持不完善
python
qq_283720051 小时前
Python教程: sys模块入门学习
python·sys
瑶总迷弟1 小时前
Python入门第6章:字典(键值对数据结构)
java·数据结构·python
第一程序员1 小时前
Python游戏开发:从入门到实践
python·github
Yao.Li2 小时前
Dify 本地环境忘记登录密码问题排障文档
人工智能·python