概述
classcollections.Counter([iterable-or-mapping])文档中对Counter类型的说明如下:
A Counter is a dict subclassfor counting hashable objects. It is an unordered collection whereelements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. TheCounter class is similar to bags or multisets in other languages. 例如:
c = Counter()
c = Counter('gallant')
c = Counter({'red':4,'blue':2})
c = Counter(cats = 4, dogs = 8)Counter类型拥有字典类型的函数接口,并且对于不存在于Counter对象中的键返回0而不是引发一个TypeError。Counter对象除了支持字典对象的方法另外有三个方法可用:
elements()
Return an iterator over elements repeating each as many times as its count. Elements are returned in arbitrary order. If an element’s count is less than one,elements() will ignore it.
>>> c = Counter('gallant')
>>> c
Counter({'a': 2, 'l': 2, 't': 1, 'g': 1, 'n': 1})
>>> c.elements()
>>> list(c.elements())
['a', 'a', 't', 'l', 'l', 'g', 'n']
most_common([n])
>>> c.most_common(2)
[('a', 2), ('l', 2)]
subtract([iterable-or-mapping])
>>> c1 = Counter({'a':4,'b':3,'c':1,'d':2})
>>> c2 = Counter({'a':1,'b':1,'c':1,'d':4})
>>> c1.subtract(c2)
Counter({'a': 3, 'b': 2})Counter没有实现dict类型的fromkeys方法,并且update()方法的工作方式也不同于dict类型:
>>> c2.update(c2)
>>> c2
Counter({'d': 8, 'a': 2, 'c': 2, 'b': 2})常见类型与Counter对象协作方式:
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-1:-1] # n least common elements
c += Counter() # remove zero and negative counts另外,Counter类型也支持一些数学运算符:
>>> 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})
REF:Python 2.7.8 documentation
最后
以上就是天真柜子为你收集整理的python中collections中的counter类_[Python]collections模块中的Counter类的全部内容,希望文章能够帮你解决python中collections中的counter类_[Python]collections模块中的Counter类所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复