# Python标准库--collections模块的Counter类

``````>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
``````

``````>>> c = Counter()             # 创建了一个空的Counter对象
>>> c = Counter('gallahad')               # 用可迭代对象创建了一个Counter对象
>>> c = Counter({'red': 4, 'blue': 2})    # 用映射来创建一个Counter
>>> c = Counter(cats=4, dogs=8)     #用关键字参数创建Counter
``````

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

most_common(n)是个返回n个最常见元素和它的计数的函数，如果n被省略或者为None，则返回所有的元素和它的计数。

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

``````>>> 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还支持几个数学运算，包括加法和减法，交集和并集。这里交集和并集返回的是对应计数的最小值和最大值。这四个运算可以接受带符号的计数值，但是与substract()不同的是，输出只包括计数值大于0的键值对。

``````>>> 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 = Counter(a=2, b=-4)
>>> +c
Counter({'a': 2})
>>> -c
Counter({'b': 4})
``````