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

欢迎大家讨论交流~


相关推荐
狗都不学爬虫_14 小时前
JS逆向 - Akamai阿迪达斯(三次) 补环境、纯算
javascript·爬虫·python·网络爬虫·wasm
深蓝海拓14 小时前
基于QtPy (PySide6) 的PLC-HMI工程项目(一)使用自定义socket协议的基本方法
python·plc
秃头狂魔14 小时前
【HOT100】DAY2
python·算法
程序员三藏14 小时前
接口自动化测试思路和实战:编写线性测试脚本实战
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
丁当粑粑14 小时前
Pydantic的主要用法
python
哈伦201914 小时前
第二章 Python语法基础
python·语法·anaconda3
Clavis14 小时前
我给 Mac 的 Photo Booth 写了自动化脚本。为什么隐私比你想的重要得多
人工智能·python
龙文浩_14 小时前
AI机器学习中NumPy随机种子的应用
人工智能·python·深度学习·神经网络·机器学习
大江东去浪淘尽千古风流人物14 小时前
【Basalt】 VIO(sqrt_keypoint_vio)主流程measure函数梳理
数据库·人工智能·python·机器学习·oracle
FelixZhang02815 小时前
从 PDF 到 AI 知识库:RAG 数据预处理的六步标准流水线 (SOP)
人工智能·python·目标检测·计算机视觉·语言模型·ocr·numpy