最常见的方法,构建一个字典,对于句子中出现的字母,如果是首次出现,则值置为1,后后面再出现就加1.
def letter_frequency_1(sentence): frequencies={} for letter in sentence: if letter not in frequencies: frequencies[letter]=1 else: frequencies[letter]+=1 return frequencies
对于setdefault方法,如果键在字典中,该方法的行为如同get方法:返回该健的值。相反,如果键不在字典中,它会设置该键的值,然后返回字典中该键的值。
def letter_frequency_2(sentence): frequencies={} for letter in sentence: frequency=frequencies.setdefault(letter,0) frequencies[letter]=frequency+1 return frequencies
下面的代码中,如果字母在defaultdict中不存在,则访问它时会返回0,之后每找到一个则会加1.
def letter_frequency_3(sentence): frequencies=defaultdict(int) for letter in sentence: frequencies[letter]+=1 return frequencies