Python collections
生成字典并初始化为0
In
from collections import defaultdict
def get_counts(sequence):
counts = defaultdict(int) # 所有的值均会被初始化为0
for x in sequence:
counts[x] += 1
return counts
get_counts('defaultdict')
Out
defaultdict(int,
{'d': 2,
'e': 1,
'f': 1,
'a': 1,
'u': 1,
'l': 1,
't': 2,
'i': 1,
'c': 1})