1.定義函數(shù)
def get_counts(sequence):
??? counts={}
??? for x in sequence:
??????? if x? in counts:
??????????? counts[x]+= 1
???????? else:
????????????? counts[x]=1
??? return counts
2.定義函數(shù)(利用python標(biāo)準(zhǔn)包)
from collections import defaultdict
def get_counts2(sequence):
??? counts=defaultdict(int)#所以得值均會(huì)被初始化W為0
??? for x in sequence:
??????? if x? in counts:
??????????? counts[x]+= 1
??? return counts
3.python標(biāo)準(zhǔn)庫(kù)中找到collections.Counter類
from collections improt Counter
counter(sequence)