4.5中collections.Counter记录
2021-03-09 本文已影响0人
richybai
collections.Counter
是对可迭代对象进行计数的对象。
其使用方法如下:类似于字典对对象出现的次数进行统计。
from collections import Counter
c = Counter(input) #对input进行统计,并创建Counter对象c
c.update(other) #添加other中出现的元素及其数量到c中
c.subtract(other) #去掉other中出现的
c.most_common(int) #返回前int个出现次数最多的元素及其个数,类型为list of tuple.
c.elements() #获得原始数据,迭代器
c.items() #获得字典item,输出时候用
del c[object] #删除对object的统计
作用的类型可以是list
,string
,dict
,tuple
等可迭代类型。
下面给出一些示例:
>>> from collections import Counter
>>> c = Counter("asdfasdfg")
>>> c
Counter({'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 1})
>>> c.elements()
<itertools.chain object at 0x00000183842D90B8>
>>> c.items()
dict_items([('a', 2), ('s', 2), ('d', 2), ('f', 2), ('g', 1)])
>>> c.update("asdf")
>>> c
Counter({'a': 3, 's': 3, 'd': 3, 'f': 3, 'g': 1})
>>> del c["g"]
>>> c
Counter({'a': 3, 's': 3, 'd': 3, 'f': 3})
>>> c.update("g")
>>> c
Counter({'a': 3, 's': 3, 'd': 3, 'f': 3, 'g': 1})
>>> c.subtract("asdfg")
>>> c
Counter({'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 0})
>>> c["e"]
0 #索引未出现的数据时,返回也是0,而不是keyerror
>>> c
Counter({'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 0})
>>> c.most_common(3)
[('a', 2), ('s', 2), ('d', 2)]