当前位置:

首页 > 编程开发 > Python中如何使用计数器collections.Counter?

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

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

    一. 介绍

    一个计数器工具提供快速和方便的计数,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) ) #
     
    #转换为字典后输出
    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)
    """

    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()) #
     
    #尝试转换为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']

    官方文档例子:

    # 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) 对。

    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
    相关文章 更多
    C++动态数组初始化怎么写?常用语句与代码示例
    C++动态数组初始化怎么写?常用语句与代码示例

    深入解析C++中动态数组的初始化机制,涵盖new操作符的不同用法、基本类型与类对象的初始化差异,以及为何在现代C++开发中应优先使用std::vector。

    Python安装后怎么打开:使用IDLE或命令行启动解释器
    Python安装后怎么打开:使用IDLE或命令行启动解释器

    刚在Windows安装好Python却不知道如何启动?本文详细演示如何通过开始菜单找到并打开IDLE集成开发环境,以及如何在PowerShell或命令提示符中使用python和py命令启动交互式解释器、运行.py脚本文件。包含退出解释器的方法及常见启动问题排查,帮助初学者快速验证安装成功并开始编写代码。

    Windows系统Python安装教程:下载、勾选PATH及环境变量配置
    Windows系统Python安装教程:下载、勾选PATH及环境变量配置

    针对Windows初学者的Python安装实战指南。详细讲解如何从Python官网下载匹配架构的安装包,重点演示安装首屏勾选“Add python.exe to PATH”的关键操作,并提供使用python --version和py命令验证环境变量的具体步骤,帮助新手快速搭建开发环境并排查路径问题。

    麒麟OS如何查看Python进程的运行状态
    麒麟OS如何查看Python进程的运行状态

    要想确认麒麟OS中Python程序的运行状态以及资源占用情况,我们可以这样做:用ps -ef | grep python来筛选进程;通过top命令,按P键排序查看实时负载;使用pgrep -f "script.py"精准获取PID;借助lsof -p PID验证文件打开状态。另外,还可以结合syst

    Python在Debian上如何配置SSL证书
    Python在Debian上如何配置SSL证书

    在Debian系统上配置SSL证书通常涉及以下几个步骤:安装Web服务器:首先,你需要一个Web服务器,比如Apache或Nginx。这里以Apache为例。sudo apt updatesudo apt install apache2获取SSL证书:你可以从Let’s Encrypt免费获取SSL

    统信UOS怎么安装Python开发环境
    统信UOS怎么安装Python开发环境

    要想让Python项目在统信UOS上正常运行,得先安装python3、python3-pip、python3-venv、python3-dev以及build-essential等组件。具体操作就是执行sudo apt install命令来一步到位完成安装,同时别忘了配置清华镜像源来给pip加速哦。在

    纯Python方案实现中英文全文搜索
    纯Python方案实现中英文全文搜索

    在互联网上的各类网站中,无论大小,基本上都会有一个搜索框,用来给用户对内容进行搜索,小到站点搜索,大到搜索引擎搜索。从简单的来说,搜索功能确实很简单,一个简单的select语句就可以实现数据的搜索。而从复杂的来看,无论是搜索的精度还是搜索的效率,都是有很深的研究范围的。对于简单的搜索功能来说,一个s

    Mac如何取消通过Python脚本运行的关机程序
    Mac如何取消通过Python脚本运行的关机程序

    立即在终端输入sudo shutdown -c取消倒计时关机,成功后显示“Shutdown cancelled”;若存在pmset重复任务,需再执行sudo pmset repeat cancel清除。Mac因Python脚本执行了os.system("sudo shutdown -h +10")或

    Pythonasyncio异步并发与多固定出口IP调度实战
    Pythonasyncio异步并发与多固定出口IP调度实战

    之前写过一篇同步场景下用 Python 管理多个固定出口 IP 的实践(ExitPool + requests/httpx),覆盖了健康检查、故障转移和连接池复用。但在实际业务中,越来越多的场景用 asyncio 做高并发采集或批量接口调用——异步事件循环下多出口的管理方式和同步场景完全不同:单线程

    Python在静态出口IP产品中的实战:从地址漂移巡检到多IP故障切换
    Python在静态出口IP产品中的实战:从地址漂移巡检到多IP故障切换

    写在前面:为什么静态出口 IP 不是"买了就行"不少团队在引入静态出口 IP 产品时,第一反应往往是:“地址配上去,这事就算完了。”可真到了真实业务里,静态出口 IP 真正能体现价值的地方,往往不在分配这一步,而在分配之后怎么管:地址有没有漂移,质量是否达标,某一条线路突然不可用时怎么切换,连接层又

    查看更多
    精品专题 更多
    装机必备
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows
    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    macOS软件
    macOS软件

    正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

    Mac软件 更多
    灵活计算器
    灵活计算器
    macOS/iOS/Android

    灵活计算器是一款笔记式算数应用,支持实时计算、动态关联和云端同步功能。记录、整理和输出之间的过渡会更自然,适合长期写作、做笔记或持续沉淀个人内容。

    赤友清理大师
    赤友清理大师
    macOS

    赤友清理大师是一款为 Mac 设计的智能清理优化工具,可精准扫描垃圾、大文件、重复文件等,释放磁盘空间。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

    极度公式
    极度公式
    Windows/macOS/Linux

    极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

    WINDOWS 更多
    Windows 10
    Windows 10
    Windows

    Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。

    极度公式
    极度公式
    Windows/macOS/Linux

    极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

    密码键盘
    密码键盘
    Windows/macOS/iOS/Android

    密码键盘是一款兼具安全性与便捷性的高效密码管理器。日常使用里的持续防护和信息管理会更突出,适合把安全控制放进长期使用流程中的场景。