注意学习collections庫
#定义一个偏历函数,将计数值保存在字典中:
def get_counts(sequence):
counts={}
for x in sequence:
if x in counts:
counts[x]+=1
else:
counts[x]=1
return counts
#另一种简洁方法
from collections import defaultdict
def get_counts2(sequence):
counts=defaultdict(int)#所有值被初始化为0
for x in counts:
counts[x]+=1
return counts