首页 > 编程语言 >Python中的Counter

Python中的Counter

时间:2022-12-27 16:34:12浏览次数:62  
标签:返回 Counter Python 元素 elements cats dogs

Counter 的用处

提供一种简洁的计数方法。

Counter 的 Import

from collections import Counter

Collections是一个集成了List、Dict、Purple、Set的拓展和替代品的模块。

image-20221227084708096

Counter

Counter是dict的子类,因此也像dict一样具有键和值,其中键表示元素,值表示元素出现的次数。

初始化

可以直接初始化,也可以从iterable 型,map 型或者keyword args 型中初始化。

c = Counter()                           # a new, empty counter
c = Counter('gallahad')                 # a new counter from an iterable,即统计'gallahad'中各元素出现次数
c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping,见elements方法
c = Counter(cats=4, dogs=8)             # a new counter from keyword args,见elements方法

初始化之后,可以按照字典的方式查询每个元素出现的次数。例如,用一个列表初始化Counter

c = Counter(['a','b','c','v','s', 'a'])
c['a']

输出结果为 2 ,如果要统计的元素不存在,那么返回的值是0,而不会像字典一样报错。如:

c = Counter(['a','b','c','v','s', 'a'])
c['d']

输出结果为0。

注意,和字典赋值一样,Counter也可以令某一个元素计数值为0,但并不会从Counter里将其删去。更进一步,这也说明Counter的值(计数值)可以为0甚至负数。

要想删去某个元素,应使用del c['某元素'] ,其中c是Counter实例。

附加方法

除了继承dict的一些方法外,Counter有一些附加方法

elements()

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

例如:

c = Counter(cats=4, dogs=8)
for i in c.elements():
    print(i, end=' ') 

输出结果是 cats cats cats cats dogs dogs dogs dogs dogs dogs dogs dogs

most_common([n])

返回一个列表,其中包含 n 个最常见的元素及出现次数,按常见程度由高到低排序。 如果 n 被省略或为 返回计数器中的所有元素。计数值相等的元素按首次出现的顺序排序。

例如:

c = Counter('gallahad')         
print(c.most_common())

结果:[('a', 3), ('l', 2), ('g', 1), ('h', 1), ('d', 1)]

total()

总的计数值。大部分场景下相当于len

c = Counter(a=10, b=5, c=0)
c.total()

输出15

注意:这是3.10出才出现的用法!

其余一些常见操作

c.total()                       # 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-1:-1]       # n least common elements
+c                              # remove zero and negative counts

一些数学计算

加法和减法运算是通过增加或减少相应元素的计数值来合并计数器。

交集和并集运算是返回相应计数的最小值和最大值。 相等和包括运算是对相应计数进行比较。

每种运算都可接受带符号计数的输入,但输出将排除计数为零或小于零的结果。

单目加和减(一元操作符)意思是从空计数器加或者减去。

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})
c == d                     # equality:  c[x] == d[x]  返回 False
c <= d                     # inclusion:  c[x] <= d[x]  返回 False

+c							 # 返回 Counter({'a': 3, 'b': 1})(可利用这个消去Counter中的计数值为0或负的元素)
-c							  # 返回 Counter()

参考

class collections.Counter([iterable-or-mapping])

标签:返回,Counter,Python,元素,elements,cats,dogs
From: https://www.cnblogs.com/VicoZhang/p/17008342.html

相关文章

  • Python实战—地图可视化
    今天给大家推送的是地图可视化的知识如何用Python实现地图可视化地图可视化常用于地理信息系统本节选用python中的自带库matplotlib实现地图可视化一起学习吧!   可视......
  • Python学习经历
    列表索引for循环改内容大写s=["张无忌","武则天","刘备","abc","cba"]forlstinrange(len(s)):x=s[lst].upper()s[lst]=xprint(s)......
  • python——发送mqtt消息
    (1)创建mqtt连接参考https://www.jianshu.com/p/06d23de47aed文中写的发布消息代码如下:文件名:mypub.py#!/usr/bin/envpython#coding:utf-8importtimeimportjso......
  • OpenCV-Python learning-7.运算性能
    本节说明opencv-python对于性能的度量和优化。以下为代码部分:%matplotlibinlineimportcv2importmatplotlib.pyplotaspltimg=cv2.imread('e:/rotman.jpg')plt.imshow(......
  • 关于python环境中安装OpenSSL模块报错-ERROR: Could not find a version that satisfi
    因为需要在代码中importOpenSSL,笔者就准备使用pip3install的方式安装 OpenSSL,结果报如下错误:[qq5201351@localhost~]$pip3installOpenSSLERROR:Couldnotfi......
  • 高性能 Python web 框架 Blacksheep 初见
    Pythonweb框架性能对比一说到Python大家多半最先想到的就是它代码的简洁与性能的孱弱。在我所使用体验过的Pythonweb框架中Tornado性能最好,Flask次之,Django最差......
  • 10个中文成语,10种Python初学者常见错误
    哈喽兄弟们,我总结了Python中十种新手常见的错误,每一个都可以用成语来形容,看看各位遇到过多少次了!一、画蛇添足多余的分号Python语言与大多数编程语言不相同,它的......
  • URL分解之InternetCrackUrl函数——就是python的urlparse
    URL分解之InternetCrackUrl函数 背景近期使用WININET库写的一个数据上传、下载的客户端小程序,上传数据到网站服务器和从网站服务器下载数据到本地。由于,对WININET库部......
  • Python中的列表条件求和方法
    列表条件求和方法 list_data=[[1.0,'配件','522422','铝扣板用纽扣','金色','',72.0,'PC',''],[2.0,'配件','500031','十字槽沉头自钻自攻螺钉4......
  • Python循环任务,错误打包输出
    有时候,多个任务循环在跑,但不想中间任何一个错误,停止主线程,但又想在主线程运行结束后,采集运行过程中所有的错误信息。这种刁钻的想法,我自问自答,记录一下操作方法。......