Python中collections.defaultdict()使用

1、以一個例子開始:統(tǒng)計一個列表里各單詞重復(fù)次數(shù)

words = ['hello','world','nice','world']counter = dict()forkwinwords:? ? counter[kw] += 1

這樣寫肯定會報錯的,因為各詞的個數(shù)都沒有初始值,引發(fā)KeyError

2、改進一下:加入if判斷

words = ['hello','world','nice','world']counter = dict()forkwinwords:ifkwinwords:? ? ? ? counter[kw] += 1else:? ? ? ? counter[kw] = 0

3、再改進:使用setdefault()方法設(shè)置默認值

words = ['hello','world','nice','world']counter = dict()forkwinwords:? ? counter.setdefault(kw, 0)? ? counter[kw] += 1

setdefault(),需提供兩個參數(shù),第一個參數(shù)是鍵值,第二個參數(shù)是默認值,每次調(diào)用都有一個返回值,如果字典中不存在該鍵則返回默認值,如果存在該鍵則返回該值,利用返回值可再次修改代碼。

words = ['hello','world','nice','world']counter = dict()forkwinwords:? ? counter[kw] = counter.setdefault(kw, 0) + 1

4、接著改進

一種特殊類型的字典本身就保存了默認值defaultdict(),defaultdict類的初始化函數(shù)接受一個類型作為參數(shù),當(dāng)所訪問的鍵不存在的時候,可以實例化一個值作為默認值。

from collections import defaultdictdd = defaultdict(list)defaultdict(, {})#給它賦值,同時也是讀取dd['h'h]defaultdict(, {'hh': []})dd['hh'].append('haha')defaultdict(, {'hh': ['haha']})

該類除了接受類型名稱作為初始化函數(shù)的參數(shù)之外,還可以使用任何不帶參數(shù)的可調(diào)用函數(shù),到時該函數(shù)的返回結(jié)果作為默認值,這樣使得默認值的取值更加靈活。

>>> from collections import defaultdict>>>defzero():...? ? return0...>>> dd = defaultdict(zero)>>> dddefaultdict(, {})>>> dd['foo']0>>> dddefaultdict(, {'foo':0})

最終代碼:

fromcollectionsimportdefaultdictwords = ['hello','world','nice','world']#使用lambda來定義簡單的函數(shù)counter = defaultdict(lambda:0)forkwinwords:? ? counter[kw] +=1

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容