計算可迭代集合中所有專案的所有出現。計數器
from collections import Counter
c = Counter(["a", "b", "c", "d", "a", "b", "a", "c", "d"])
c
# Out: Counter({'a': 3, 'b': 2, 'c': 2, 'd': 2})
c["a"]
# Out: 3
c[7] # not in the list (7 occurred 0 times!)
# Out: 0
collections.Counter
可用於任何迭代,並計算每個元素的每次出現次數。
注意 :一個例外是如果給出 dict
或類似 collections.Mapping
的類,那麼它將不計算它們,而是建立一個具有這些值的 Counter:
Counter({"e": 2})
# Out: Counter({"e": 2})
Counter({"e": "e"}) # warning Counter does not verify the values are int
# Out: Counter({"e": "e"})