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

欢迎大家讨论交流~


相关推荐
Hui Baby6 小时前
Python Flask 多文件项目打包部署(Linux+Docker+Windows 全环境)
linux·python·flask
忆~遂愿6 小时前
vLLM Ascend 项目架构解析与部署配置指南
人工智能·后端·python·ai
yuan20416 小时前
PyCharm 安装 dlib 库
python·pycharm·dlib
Q_Q19632884756 小时前
python+django/flask+vue基于机器学习的就业岗位推荐系统
spring boot·python·django·flask·node.js
艾上编程6 小时前
Python 跨场景实战:从爬虫采集到 AI 部署的落地指南
python·数据分析·自动化
serve the people6 小时前
tensorflow 零基础吃透:不规则维度 vs 均匀维度(RaggedTensor 核心概念)
人工智能·python·tensorflow
南极星10056 小时前
OPENCV(python)--初学之路(十六)SURF简介
python·opencv·算法
Q_Q5110082856 小时前
python+django/flask+vue基于深度学习的图书推荐系统
spring boot·python·django·flask·node.js·php
sugar椰子皮6 小时前
【爬虫框架-5】实现一下之前的思路
开发语言·爬虫·python
码界奇点6 小时前
基于Flask与Vue.js的百度网盘自动转存系统设计与实现
vue.js·python·flask·自动化·毕业设计·源代码管理