– Start
Python collections 包提供了好多集合模块,下面我们通过例子来看一下。
Counter
Counter 是 dict 的子类,用来统计数量,下面的例子统计每个单词出现的次数。
from collections import Counter
# 统计单词出现的次数
sentense = 'what is this? this is an apple.'
r = Counter(sentense.split())
print(r)
结果如下。
Counter({
'is': 2, 'what': 1, 'this?': 1, 'this': 1, 'an&