【Python】字典的setdefault()方法

Layson4869發表於2020-11-21

在這裡插入圖片描述
這是一道統計目標句子中單片語合出現次數的題目,輸出的是一個字典:

wordstring = 'it was the best of times it was the worst of times \
it was the age of wisdom it was the age of foolishness'

# write your code below

def get_pair_freq1(wordstring):
    wordlist = wordstring.split(" ") #分解成字串列表
    dic = {}
    for i in range(0,len(wordlist)-1):
        if (wordlist[i],wordlist[i+1]) not in dic.keys():#識別單片語合是否已在字典中
            dic[wordlist[i],wordlist[i+1]] = 1 #如果沒有則初始化鍵值對,該單片語合對應出現次數為1
        else:
            dic[wordlist[i],wordlist[i+1]] += 1 #如果已在字典中,則該單片語合對應出現次數+1
    return dic

get_pair_freq(wordstring)

當為字典中某個鍵設定預設值時,如果該鍵沒有任何值,我們一般會用到類似上面的if語句;而setdefault()方法同樣可行,它傳入的第一個引數是要檢查的鍵,第二個引數是如果該鍵不存在時要設定的值,如果該鍵存在,則不會改變該鍵的值。

def get_pair_freq2(wordstring):
    wordlist = wordstring.split(" ")
    dic = {}
    for i in range(0,len(wordlist)-1):
        dic.setdefault((wordlist[i],wordlist[i+1]),0)
        dic[wordlist[i],wordlist[i+1]] += 1
    return dic

get_pair_freq(wordstring)

相關文章