计算可迭代集合中所有项目的所有出现。计数器
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"})