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

欢迎大家讨论交流~


相关推荐
开发者小天6 分钟前
python中For Loop的用法
java·服务器·python
老百姓懂点AI43 分钟前
[RAG实战] 向量数据库选型与优化:智能体来了(西南总部)AI agent指挥官的长短期记忆架构设计
python
喵手3 小时前
Python爬虫零基础入门【第九章:实战项目教学·第15节】搜索页采集:关键词队列 + 结果去重 + 反爬友好策略!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·搜索页采集·关键词队列
Suchadar3 小时前
if判断语句——Python
开发语言·python
ʚB҉L҉A҉C҉K҉.҉基҉德҉^҉大3 小时前
自动化机器学习(AutoML)库TPOT使用指南
jvm·数据库·python
喵手3 小时前
Python爬虫零基础入门【第九章:实战项目教学·第14节】表格型页面采集:多列、多行、跨页(通用表格解析)!
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·表格型页面采集·通用表格解析
0思必得04 小时前
[Web自动化] 爬虫之API请求
前端·爬虫·python·selenium·自动化
莫问前路漫漫4 小时前
WinMerge v2.16.41 中文绿色版深度解析:文件对比与合并的全能工具
java·开发语言·python·jdk·ai编程
木头左4 小时前
Backtrader框架下的指数期权备兑策略资金管理实现与风险控制
python
玄同7654 小时前
LangChain 核心组件全解析:构建大模型应用的 “乐高积木”
人工智能·python·语言模型·langchain·llm·nlp·知识图谱