[Python] Not just count collections.Counter

Overview

We have summarized the nature of collections.Counter that gets the number of elements of iterable. Besides counting, it has other useful properties that dict does not have, so I would like to actively use it.

Calculation

Addition / subtraction and set calculation are possible. Keys whose value is less than or equal to zero are automatically deleted.

from collections import Counter

A = Counter('ab') # Counter({'a': 1, 'b': 1})
B = Counter('bc') # Counter({'c': 1, 'b': 1})
A + B # Counter({'b': 2, 'a': 1, 'c': 1})
A - B # Counter({'a': 1})
A & B # Counter({'b': 1})
A | B # Counter({'a': 1, 'b': 1, 'c': 1})

Method

Unlike operators, keys with values less than or equal to zero are also retained. ʻElements` returns only keys with positive values.

from collections import Counter

A = Counter('ab')
B = Counter('bc')
C = Counter('ac')
C.update(A) # Counter({'a': 2, 'c': 1, 'b': 1})
A.subtract(B) # Counter({'a': 1, 'b': 0, 'c': -1})
A.most_common() # [('a', 1), ('b', 0), ('c', -1)]
sorted(C.elements()) # ['a', 'a', 'b', 'c']
sorted(A.elements()) # ['a']

reference

If you change the element directly, the value below zero is allowed as in the method. References to non-existent elements return 0 without exception.

from collections import Counter

A = Counter('ab')
A['a'] += 2 # Counter({'a': 3, 'b': 1})
a['b'] -= 2 # Counter({'a': 3, 'b': -1})
A['c'] # 0

The unary operator is a shortcut for operations on the empty Counter (). Only positive or negative values can be extracted after the operation for each element.

A # Counter({'a': 3, 'b': -1})
+A # Counter({'a': 3})
-A # Counter({'b': 1})

Recommended Posts

[Python] Not just count collections.Counter
Python Not Implemented Error
Not just list comprehension
Count up list using collections.Counter
Python round is not strictly round
filter rollbar python 404 not found
Python list is not a list
Did not change from Python 2 to 3
Python does not output errors or output just because the indent is misaligned