Section 73.1: 计算迭代器中所有项目的所有出现次数:collections.Counter
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"})

Section 73.2: 获取最常见的值(-s): collections.Counter.most_common()
使用 collections.Counter 无法计算映射的键值,但我们可以计算值:
from collections import Counter
adict = {'a': 5, 'b': 3, 'c': 5, 'd': 2, 'e':2, 'q': 5}
Counter(adict.values())
# Out: Counter({2: 2, 3: 1, 5: 3})
最常见的元素可通过 most_common-method 调用:
# Sorting them from most-common to least-common value:
Counter(adict.values()).most_common()
# Out: [(5, 3), (2, 2), (3, 1)]
# Getting the most common value
Counter(adict.values()).most_common(1)
# Out: [(5, 3)]
# Getting the two most common values
Counter(adict.values()).most_common(2)
# Out: [(5, 3), (2, 2)]

Section 73.3: 计算序列中一个项目的出现次数:list.count() 和 tuple.count()
alist = [1, 2, 3, 4, 1, 2, 1, 3, 4]
alist.count(1)
# Out: 3
atuple = ('bear', 'weasel', 'bear', 'frog')
atuple.count('bear')
# Out: 2
atuple.count('fox')
# Out: 0

Section 73.4: 计算字符串中子串的出现次数: str.count()
astring = 'thisisashorttext'
astring.count('t')
# Out: 4
这对长度超过一个字符的子串也有效:
astring.count('th')
# Out: 1
astring.count('is')
# Out: 2
astring.count('text')
# Out: 1
而 collections.Counter 只计算单个字符:
from collections import Counter
Counter(astring)
# Out: Counter({'a': 1, 'e': 1, 'h': 2, 'i': 2, 'o': 1, 'r': 1, 's': 3, 't': 4, 'x': 1})

Section 73.5: 计算 numpy 数组中的出现次数
计算数值在 numpy 数组中的出现次数。这样就可以了:
>>> import numpy as np
>>> a=np.array([0,3,4,3,5,4,7])
>>> print(np.sum(a==3))
2
其逻辑是,布尔语句会产生一个数组,在该数组中,所有要求值的出现次数均为 1,而其他值均为 0。因此,将这些值相加就得到了出现的次数。这适用于任何形状或 d 类型的数组。
我使用两种方法来计算 numpy 中所有唯一值的出现次数。Unique 和 bincount。Unique 可以自动对多维数组进行扁平化处理,而 bincount 只适用于只包含正整数的 1d 数组。
>>> unique,counts=np.unique(a,return_counts=True)
>>> print(unique,counts) # counts[i] is equal to occurrences of unique[i] in a
[0 3 4 5 7] [1 2 2 1 1]
>>> bin_count=np.bincount(a)
>>> print(bin_count) # bin_count[i] is equal to occurrences of i in a
[1 0 0 2 2 1 0 1]
如果数据是 numpy 数组,通常使用 numpy 方法比将数据转换为通用方法要快得多。
