使用collection.Counter实现统计简化

背景介绍

在python的应用场景中,我们常常需要通过建立统计表来对某一个数据集中某些数据出现次数的统计,这时候经常会使用到python的字典数据类型建立映射表,一般的方法可能会比较繁琐,本篇博客介绍collection.Counter方法帮助简化统计出现数量的过程

任务设计

统计字符串‘fbhsiagfhiwagbourahlbgojlrghboajwbhifalbg’中每个字母出现的次数

直接统计

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)

结果

{'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

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进一步简化

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

欢迎大家讨论交流~


相关推荐

  1. 统一登陆实现简化流程

    2024-01-26 11:54:05       14 阅读
  2. 使用WebRTC实现简单直播

    2024-01-26 11:54:05       14 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-26 11:54:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-26 11:54:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-26 11:54:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-26 11:54:05       18 阅读

热门阅读

  1. kotlin sum 与 sumOf

    2024-01-26 11:54:05       35 阅读
  2. Android.bp 语

    2024-01-26 11:54:05       37 阅读
  3. kotlin中的初始化问题纪录

    2024-01-26 11:54:05       31 阅读
  4. 大厂程序员成长路径

    2024-01-26 11:54:05       38 阅读
  5. 深度挖掘:前端架构设计与现代化实践

    2024-01-26 11:54:05       34 阅读
  6. golang视角下 protobuf 的安装 从proto文件到go文件

    2024-01-26 11:54:05       31 阅读
  7. 看书标记【数据科学:R语言实战 1】

    2024-01-26 11:54:05       32 阅读