Python collections.Counter()使用例子详解

我们有时候会用Python字典计数,实际上collections.Counter就是让这个计数更方便了一些

计数

>>> c = Counter() #实例化
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     c[word] += 1 #每次只要写一下这个即可
>>> c
Counter({'blue': 3, 'red': 2, 'green': 1})

枚举counter中的元素

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']

Counter的初始化

>>> c = Counter() #空的
>>> sorted(c.elements())
[]

>>> c = Counter('gallahad') #通过输入一个iterable来创立
>>> sorted(c.elements())
['a', 'a', 'a', 'd', 'g', 'h', 'l', 'l']

>>> c = Counter({'red': 4, 'blue': 2})
>>> sorted(c.elements())
['blue', 'blue', 'red', 'red', 'red', 'red']

>>> c = Counter(cats=4, dogs=8)
>>> sorted(c.elements())
['cats', 'cats', 'cats', 'cats', 'dogs', 'dogs', 'dogs', 'dogs', 'dogs', 'dogs', 'dogs', 'dogs']

#还可以直接把列表转为counter
>>> c = Counter(['cats', 'cats', 'cats', 'cats', 'dogs', 'dogs', 'dogs', 'dogs', 'dogs', 'dogs', 'dogs', 'dogs'])

返回前n个出现次数最多的元素

>>> Counter('abracadabra').most_common(3)
#n=3
[('a', 5), ('b', 2), ('r', 2)]

从counter1的每一个类别减去counter2对应类别的数目

>>> 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})

另外Counter支持集合的±&|

>>> a  = Counter({"m":1,"n":2})
>>> b = Counter({"m":3,"n":4})
>>> a+b
Counter({'n': 6, 'm': 4})
>>> b-a
Counter({'m': 2, 'n': 2})
>>> a&b #每个元素取最小值
Counter({'n': 2, 'm': 1})
>>> a|b #每个元素取最大值
>Counter({'n': 4, 'm': 3})

Reference

https://docs.python.org/zh-cn/3/library/collections.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值