Python Glossary Русский

all Python 3collectionsterm

collections.Counter

counter

A dictionary for counting items. Methods: most_common(n), elements(); it also supports +, -, & and |.

Syntax

collections.Counter([iterable-or-mapping])

Looking up a missing key returns 0 and, unlike defaultdict, does not insert anything — convenient, but a typo in a key silently yields 0 instead of a KeyError. Note also that the subtraction operator c1 - c2 drops zero and negative counts, while the subtract() method keeps them, so of the two only subtract() can yield negative counts (one can also be assigned directly: c[x] = -1). most_common() sorts by descending count and breaks ties by first-encountered order.

Examples

from collections import Counter
c = Counter('aabbccca')
print(c)
# → Counter({'a': 3, 'c': 3, 'b': 2})
print(c.most_common(2))
# → [('a', 3), ('c', 3)]
from collections import Counter
c2 = Counter(['apple', 'banana', 'apple', 'cherry', 'apple'])
print(c2.most_common(1))
# → [('apple', 3)]
from collections import Counter
c3 = Counter('hello')
c4 = Counter('world')
print(c3 + c4)
# → Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 1})
print(c3 - c4)
# → Counter({'h': 1, 'e': 1, 'l': 1}) (только положительные)
print(c3 & c4)
# → Counter({'l': 1, 'o': 1}) (пересечение, min)
print(c3 | c4)
# → Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1, 'w': 1, 'r': 1, 'd': 1}) (объединение, max)
from collections import Counter
words = 'the cat sat on the mat'.split()
wc = Counter(words)
print(wc.most_common(3))
# → [('the', 2), ('cat', 1), ('sat', 1)]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy