美文网首页
4.5中collections.Counter记录

4.5中collections.Counter记录

作者: richybai | 来源:发表于2021-03-09 11:15 被阅读0次

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

相关文章

网友评论

      本文标题:4.5中collections.Counter记录

      本文链接:https://www.haomeiwen.com/subject/oobvqltx.html