1.定义函数
def get_counts(sequence):
counts={}
for x in sequence:
if x in counts:
counts[x]+= 1
else:
counts[x]=1
return counts
2.定义函数(利用python标准包)
from collections import defaultdict
def get_counts2(sequence):
counts=defaultdict(int)#所以得值均会被初始化W为0
for x in sequence:
if x in counts:
counts[x]+= 1
return counts
3.python标准库中找到collections.Counter类
from collections improt Counter
counter(sequence)