Python 计数器:如何使用 collections.Counter?

小丽君_3713

小丽君_3713

2023-05-08

1478人浏览

转载

    一. 介绍

    一个计数器工具提供快速和方便的计数,counter是一个dict的子类,用于计数可哈希对象。它是一个集合,元素像字典键(key)一样存储,它们的计数存储为值。计数可以是任何整数值,包括0和负数,counter类有点像其他语言中的bags或multisets。简单说,就是可以统计计数,来几个例子看看就清楚了。
    举例:

    #计算top10的单词
    from collections import Counter
    import re
    text = 'remove an existing key one level down remove an existing key one level down'
    words = re.findall(r'\w+', text)
    Counter(words).most_common(10)
    [('remove', 2),('an', 2),('existing', 2),('key', 2),('one', 2)('level', 2),('down', 2)] 
    
    
    #计算列表中单词的个数
    cnt = Counter()
    for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
        cnt[word] += 1
    cnt
    Counter({'red': 2, 'blue': 3, 'green': 1})
    
    
    #上述这样计算有点嘛,下面的方法更简单,直接计算就行
    L = ['red', 'blue', 'red', 'green', 'blue', 'blue'] 
    Counter(L)
    Counter({'red': 2, 'blue': 3, 'green': 1}

    元素从一个iterable 被计数或从其他的mapping (or counter)初始化:

    from collections import Counter
    
    #字符串计数
    Counter('gallahad') 
    Counter({'g': 1, 'a': 3, 'l': 2, 'h': 1, 'd': 1})
    
    #字典计数
    Counter({'red': 4, 'blue': 2})  
    Counter({'red': 4, 'blue': 2})
    
    #计数
    Counter(cats=4, dogs=8)
    Counter({'cats': 4, 'dogs': 8})
    
    Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
    Counter({'red': 2, 'blue': 3, 'green': 1})

    二. 基本操作

    1. 统计“可迭代序列”中每个元素的出现的次数

    1.1 对列表/字符串作用

    下面是两种使用方法,一种是直接使用,一种是实例化以后使用,如果要频繁调用的话,显然后一种更简洁 ,因为可以方便地调用Counter内的各种方法,对于其他可迭代序列也是一样的套路。

    #首先引入该方法
    from collections import Counter
    #对列表作用
    list_01 = [1,9,9,5,0,8,0,9]  #GNZ48-陈珂生日
    print(Counter(list_01))  #Counter({9: 3, 0: 2, 1: 1, 5: 1, 8: 1})
     
    #对字符串作用
    temp = Counter('abcdeabcdabcaba')
    print(temp)  #Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
    #以上其实是两种使用方法,一种是直接用,一种是实例化以后使用,如果要频繁调用的话,显然后一种更简洁

    1.2 输出结果

    #查看类型
    print( type(temp) ) #<class>
     
    #转换为字典后输出
    print( dict(temp) ) #{'b': 4, 'a': 5, 'c': 3, 'd': 2, 'e': 1}
     
    for num,count in enumerate(dict(temp).items()):
        print(count)
    """
    ('e', 1)
    ('c', 3)
    ('a', 5)
    ('b', 4)
    ('d', 2)
    """</class>

    1.3 用自带的items()方法输出

    显然这个方法比转换为字典后再输出的方法更为方便:

    print(temp.items()) #dict_items([('e', 1), ('c', 3), ('b', 4), ('d', 2), ('a', 5)])
     
    for item in temp.items():
        print(item)
    """
    ('a', 5)
    ('c', 3)
    ('d', 2)
    ('e', 1)
    ('b', 4)
    """

    2. most_common()统计出现次数最多的元素

    利用most_common()方法,返回一个列表,其中包含n个最常见的元素及出现次数,按常见程度由高到低排序。 如果 n 被省略或为None,most_common() 将返回计数器中的所有元素,计数值相等的元素按首次出现的顺序排序,经常用来计算top词频的词语:

    #求序列中出现次数最多的元素
     
    from collections import Counter
     
    list_01 = [1,9,9,5,0,8,0,9]
    temp = Counter(list_01)
     
    #统计出现次数最多的一个元素
    print(temp.most_common(1))   #[(9, 3)]  元素“9”出现3次。
    print(temp.most_common(2)) #[(9, 3), (0, 2)]  统计出现次数最多个两个元素
     
    #没有指定个数,就列出全部
    print(temp.most_common())  #[(9, 3), (0, 2), (1, 1), (5, 1), (8, 1)]
    Counter('abracadabra').most_common(3)
    [('a', 5), ('b', 2), ('r', 2)]
    
    Counter('abracadabra').most_common(5)
    [('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]

    3. elements() 和 sort()方法

    描述:返回一个迭代器,其中每个元素将重复出现计数值所指定次。 元素会按首次出现的顺序返回。 如果一个元素的计数值小于1,elements() 将会忽略它。
    举例:

    c = Counter(a=4, b=2, c=0, d=-2)
    list(c.elements())
    ['a', 'a', 'a', 'a', 'b', 'b']
    
    sorted(c.elements())
    ['a', 'a', 'a', 'a', 'b', 'b']
    
    c = Counter(a=4, b=2, c=0, d=5)
    list(c.elements())
    ['a', 'a', 'a', 'a', 'b', 'b', 'd', 'd', 'd', 'd', 'd']
    from collections import Counter
     
    c = Counter('ABCABCCC')
    print(c.elements()) #<itertools.chain>
     
    #尝试转换为list
    print(list(c.elements())) #['A', 'A', 'C', 'C', 'C', 'C', 'B', 'B']
     
    #或者这种方式
    print(sorted(c.elements()))  #['A', 'A', 'B', 'B', 'C', 'C', 'C', 'C']
     
    #这里与sorted的作用是: list all unique elements,列出所有唯一元素
    #例如
    print( sorted(c) ) #['A', 'B', 'C']</itertools.chain>

    官方文档例子:

    # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
    prime_factors = Counter({2: 2, 3: 3, 17: 1})
    product = 1
    for factor in prime_factors.elements():  # loop over factors
        product *= factor  # and multiply them
    print(product)  #1836
    #1836 = 2*2*3*3*3*17

    4. subtract()减操作:输出不会忽略掉结果为零或者小于零的计数

    从迭代对象或映射对象减去元素,输入和输出都可以是0或者负数。

    c = Counter(a=4, b=2, c=0, d=-2)
    d = Counter(a=1, b=2, c=3, d=4)
    c.subtract(d)
    c
    Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
    
    #减去一个abcd
    str0 = Counter('aabbccdde')
    str0
    Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2, 'e': 1})
    
    str0.subtract('abcd')
    str0
    Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1}
    subtract_test01 = Counter("AAB")
    subtract_test01.subtract("BCC")
    print(subtract_test01)  #Counter({'A': 2, 'B': 0, 'C': -2})

    这里的计数可以减到零一下,可以包含零和负数:

    subtract_test02 = Counter("which")
    subtract_test02.subtract("witch")  #从另一个迭代序列中减去元素
    subtract_test02.subtract(Counter("watch"))  #^……
     
    #查看结果
    print( subtract_test02["h"] )  # 0 ,whirch 中两个,减去witch中一个,减去watch中一个,剩0个
    print( subtract_test02["w"] )  #-1

    5. 字典方法

    通常字典方法都可用于Counter对象,除了有两个方法工作方式与字典并不相同。

    • fromkeys(iterable):这个类方法没有在Counter中实现。

    • update([iterable-or-mapping]):从迭代对象计数元素或者从另一个映射对象 (或计数器) 添加,元素个数是加上。另外迭代对象应该是序列元素,而不是一个 (key, value) 对。

      在清理重构之前使用 Vulture 查找未使用的 Python 代码
      在清理重构之前使用 Vulture 查找未使用的 Python 代码

      在重构之前对Python代码库运行死代码检测,以便智能体能够标记未使用的函数、类、导入和变量,而不是盲目删除。

      下载
    sum(c.values())                 # total of all counts
    c.clear()                       # reset all counts
    list(c)                         # list unique elements
    set(c)                          # convert to a set
    dict(c)                         # convert to a regular dictionary
    c.items()                       # convert to a list of (elem, cnt) pairs
    Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
    c.most_common(n)                   # n least common elements
    +c                              # remove zero and negative counts

    6. 数学操作

    这个功能非常强大,提供了几个数学操作,可以结合 Counter 对象,以生产 multisets (计数器中大于0的元素)。 加和减,结合计数器,通过加上或者减去元素的相应计数。交集和并集返回相应计数的最小或最大值。每种操作都可以接受带符号的计数,但是输出会忽略掉结果为零或者小于零的计数。

    c = Counter(a=3, b=1)
    d = Counter(a=1, b=2)
    c + d                       # add two counters together:  c[x] + d[x]
    Counter({'a': 4, 'b': 3})
    c - d                       # subtract (keeping only positive counts)
    Counter({'a': 2})
    c & d                       # intersection:  min(c[x], d[x]) 
    Counter({'a': 1, 'b': 1})
    c | d                       # union:  max(c[x], d[x])
    Counter({'a': 3, 'b': 2})
    print(Counter('AAB') + Counter('BCC'))
    #Counter({'B': 2, 'C': 2, 'A': 2})
    print(Counter("AAB")-Counter("BCC"))
    #Counter({'A': 2})

    与”和“或”操作:

    print(Counter('AAB') & Counter('BBCC'))
    #Counter({'B': 1})
     
    print(Counter('AAB') | Counter('BBCC'))
    #Counter({'A': 2, 'C': 2, 'B': 2})

    单目加和减(一元操作符)意思是从空计数器加或者减去,相当于给计数值乘以正值或负值,同样输出会忽略掉结果为零或者小于零的计数:

    c = Counter(a=2, b=-4)
    +c
    Counter({'a': 2})
    -c
    Counter({'b': 4})

    写一个计算文本相似的算法,加权相似:

    def str_sim(str_0,str_1,topn):
        topn = int(topn)
        collect0 = Counter(dict(Counter(str_0).most_common(topn)))
        collect1 = Counter(dict(Counter(str_1).most_common(topn)))       
        jiao = collect0 & collect1
        bing = collect0 | collect1       
        sim = float(sum(jiao.values()))/float(sum(bing.values()))        
        return(sim)         
    
    str_0 = '定位手机定位汽车定位GPS定位人定位位置查询'         
    str_1 = '导航定位手机定位汽车定位GPS定位人定位位置查询'         
    
    str_sim(str_0,str_1,5)    
    0.75

    7. 计算元素总数、Keys() 和 Values()

    from collections import Counter
     
    c = Counter('ABCABCCC')
    print(sum(c.values()))  # 8  total of all counts
     
    print(c.keys())  #dict_keys(['A', 'B', 'C'])
    print(c.values())  #dict_values([2, 2, 4])

    8. 查询单元素结果

    from collections import Counter
    c = Counter('ABBCC')
    #查询具体某个元素的个数
    print(c["A"])  #1

    9. 添加

    for elem in 'ADD':  # update counts from an iterabl
        c[elem] += 1
    print(c.most_common())  #[('C', 2), ('D', 2), ('A', 2), ('B', 2)]
    #可以看出“A”增加了一个,新增了两个“D”

    10. 删除(del)

    del c["D"]
    print(c.most_common())  #[('C', 2), ('A', 2), ('B', 2)]
    del c["C"]
    print(c.most_common())  #[('A', 2), ('B', 2)]

    11. 更新 update()

    d = Counter("CCDD")
    c.update(d)
    print(c.most_common())  #[('B', 2), ('A', 2), ('C', 2), ('D', 2)]

    12. 清除 clear()

    c.clear()
    print(c)  #Counter()

    三. 总结

    Counter是一个dict子类,主要是用来对你访问的对象的频率进行计数。

    常用方法:

    • elements():返回一个迭代器,每个元素重复计算的个数,如果一个元素的计数小于1,就会被忽略。

    • most_common([n]):返回一个列表,提供n个访问频率最高的元素和计数

    • subtract([iterable-or-mapping]):从迭代对象中减去元素,输入输出可以是0或者负数,不同于减号 - 的作用

    • update([iterable-or-mapping]):从迭代对象计数元素或者从另一个 映射对象 (或计数器) 添加。

    举例:

    # 统计字符出现的次数
    >>> import collections
    >>> collections.Counter('hello world')
    Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
    # 统计单词数
    >>> collections.Counter('hello world hello world hello nihao'.split())
    Counter({'hello': 3, 'world': 2, 'nihao': 1})

    常用的方法:

    >>> c = collections.Counter('hello world hello world hello nihao'.split())
    >>> c
    Counter({'hello': 3, 'world': 2, 'nihao': 1})
    # 获取指定对象的访问次数,也可以使用get()方法
    >>> c['hello']
    3
    >>> c = collections.Counter('hello world hello world hello nihao'.split())
    # 查看元素
    >>> list(c.elements())
    ['hello', 'hello', 'hello', 'world', 'world', 'nihao']
    # 追加对象,或者使用c.update(d)
    >>> c = collections.Counter('hello world hello world hello nihao'.split())
    >>> d = collections.Counter('hello world'.split())
    >>> c
    Counter({'hello': 3, 'world': 2, 'nihao': 1})
    >>> d
    Counter({'hello': 1, 'world': 1})
    >>> c + d
    Counter({'hello': 4, 'world': 3, 'nihao': 1})
    # 减少对象,或者使用c.subtract(d)
    >>> c - d
    Counter({'hello': 2, 'world': 1, 'nihao': 1})
    # 清除
    >>> c.clear()
    >>> c
    Counter()

    Python免费学习笔记(深入):立即使用
    在学习笔记中,你将探索 Python 的核心概念和高级技巧!

    相关文章

    python速学教程(入门到精通)
    python速学教程(入门到精通)

    python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

    下载

    相关标签:

    python

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

    相关专题

    更多
    GoFrame框架Web开发与路由中间件
    GoFrame框架Web开发与路由中间件

    本专题聚焦GoFrame框架的Web开发,拆解路由注册与匹配规则、请求参数获取、参数校验与中间件执行顺序,说明统一响应、JWT鉴权、文件上传与接口文档生成的落地方式,并补充优雅重启与测试实践。

    2026.11.17

    20

    15

    GoFrame框架安装与gf命令行工具
    GoFrame框架安装与gf命令行工具

    本专题围绕GoFrame框架的安装与工具链配置展开,讲清Go版本要求、gf命令行的安装方式、代理镜像与依赖准备,说明项目初始化、热编译、交叉编译打包的做法,并整理安装阶段的常见报错与验证步骤。

    2026.11.17

    60

    15

    GoFrame框架零基础入门
    GoFrame框架零基础入门

    本专题整理GoFrame框架的入门知识,从模块化设计理念、环境准备到跑通第一个Web服务,讲清目录分层、配置加载、日志与中间件的用法,并对比Gin、Go-Zero的差异,帮助Go开发者建立整体认知。

    2026.11.17

    60

    15

    SQLAlchemy 一对多关系怎么建立
    SQLAlchemy 一对多关系怎么建立

    SQLAlchemy 一对多关系怎么建立?本专题整理父子表外键、relationship 双向映射、关联查询、级联删除和加载优化等相关文章,帮助你理解并实现常见的 ORM 关系建模。

    2026.11.17

    20

    10

    SQLAlchemy 如何增删改查
    SQLAlchemy 如何增删改查

    SQLAlchemy 如何增删改查?本专题整理 ORM 新增记录、条件查询、更新和删除、Session 事务提交与批量处理等实用文章,帮助你掌握 Python 数据库操作流程。

    2026.11.17

    60

    11

    SQLAlchemy ORM 模型怎么写
    SQLAlchemy ORM 模型怎么写

    SQLAlchemy ORM 模型怎么写?本专题整理模型类定义、Mapped 字段映射、主键与约束、表结构创建和常见报错的相关文章,帮助你从基础配置到实际建模逐步掌握 SQLAlchemy。

    2026.11.17

    40

    16

    Go-Zero API开发使用教程
    Go-Zero API开发使用教程

    本专题聚焦Go-Zero的API开发,拆解.api描述文件的语法结构、路由与分组定义、参数绑定与校验规则,说明统一响应体、JWT鉴权、跨域与接口文档生成的落地方式,并给出网关聚合与接口测试的实践建议。

    2026.11.12

    180

    15

    Go-Zero安装与goctl环境配置教程
    Go-Zero安装与goctl环境配置教程

    本专题围绕Go-Zero的安装与工具链配置展开,讲清Go版本要求、goctl安装方式、代理镜像、protoc依赖与环境变量设置,说明多版本共存、升级回退与CI流水线安装的做法,并整理安装阶段的常见报错与验证步骤。

    2026.11.12

    140

    15

    Go-Zero零基础入门教程
    Go-Zero零基础入门教程

    本专题整理Go-Zero的入门知识,从框架定位、环境准备到跑通第一个API服务,讲清目录分层、配置加载、日志与中间件的基本用法,并对比Gin、Kratos的差异,帮助Go开发者建立整体认知,判断它是否适合当前项目。

    2026.11.12

    160

    15

    热门下载

    更多
    网站特效
    /
    网站源码
    /
    网站素材
    /
    前端模板

    精品课程

    更多
    相关推荐
    /
    热门推荐
    /
    最新课程