Counter 計數器

前言: 在演算法中我們有時候會需要計算可迭代物件中的個別元素數量,Python內建的Counter可以幫我們在實現這個功能之外,效能優化也是挺不錯的。


建立Counter

1
2
3
4
5
6
import collections.Counter

c = Counter() # a new, empty counter
c = Counter('gallahad') # a new counter from an iterable
c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
c = Counter(cats=4, dogs=8) # a new counter from keyword args

查看 Counter物件中該元素個數

1
2
3
4
5
import collections.Counter

c = Counter(['eggs', 'ham'])
c['bacon'] # 0
c['eggs'] # 1

刪除Counter物件中的元素記數

1
2
c['sausage'] = 0                        # counter entry with a zero count
del c['sausage'] # del actually removes the entry

列出Counter中的所有元素

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

Counter物件中重複最多次的元素

most_common(n) 可以給n來回傳前n個重複最多次的元素

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

Counter物件記數相減

1
2
3
4
c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
print(c) # Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})