Counter is a subclass of dict for counting hashable objects.
It is a collection where elements 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.
from collections import Counter
d = Counter("I have one dog and one cat".split())
print(d)
# Counter({'one': 2, 'I': 1, 'have': 1, 'dog': 1, 'and': 1, 'cat': 1})
Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a KeyError.
print(d['I'])
# 1
print(d['she'])
# 0
Methods
elements()
Return an iterator over elements repeating each as many times as its count.
If an element's count is less than one, it will be ignored.
d = Counter({'apple': 2, 'banana': 0, 'cherry': 3})
for elem in d.elements():
print(elem)
# apple
# apple
# cherry
# cherry
# cherry
most_common([n])
Return a list of the n most common elements and their counts from the most common to the least.
d = Counter('abcdeaceab')
print(d.most_common())
# [('a', 3), ('b', 2), ('c', 2), ('e', 2), ('d', 1)]
print(d.most_common(2))
# [('a', 3), ('b', 2)]
subtract([iterable-or-mapping])
Elements are subtracted from an iterable or from another mapping.
d1 = Counter(red=1, green=3, blue=5, black=0)
d2 = Counter(red=3, green=1, black=2)
d1.subtract(d2)
print(d1)
# Counter({'blue': 5, 'green': 2, 'red': -2, 'black': -2})
fromkeys(iterable)
This dict method can not use for Counter.
update([iterable-or-mapping])
Elements are counted from an iterable or added-in from another mapping.
d1 = Counter(red=1, green=3, blue=5, black=0)
d2 = Counter(red=3, green=1, black=2)
d1.update(d2)
print(d1)
# Counter({'blue': 5, 'red': 4, 'green': 4, 'black': 2})
Using Operator with Counter
d1 = Counter(a=3, b=-1, c=2)
d2 = Counter(a=-1, b=2, c=3)
#> Remove zero and negative counts
print(+d1)
# Counter({'a': 3, 'c': 2})
#> Remove zero and positive counts
print(-d1)
# Counter({'b': 1})
#> Add
print(d1 + d2)
# Counter({'c': 5, 'a': 2, 'b': 1})
#> Subract
print(d1 - d2)
# Counter({'a': 4})
#> Intersection
print(d1 & d2)
# Counter({'c': 2})
#> Union
print(d1 | d2)
# Counter({'a': 3, 'c': 3, 'b': 2})
Conclusion
If you need a counting element as a dictionary form, you should use Counter.
'Python' 카테고리의 다른 글
[Python] ChainMap in collections (0) | 2021.05.02 |
---|---|
[Python] namedtuple in collections (0) | 2021.05.02 |
[Python] OrderedDict in collections (0) | 2021.05.01 |
[Python] defaultdict in collections (0) | 2021.05.01 |
[Python] deque in collections (0) | 2021.04.30 |
댓글