以一個(gè)例子開(kāi)始:統(tǒng)計(jì)一個(gè)列表里各單詞重復(fù)次數(shù)
words = ['hello','world','nice','world']counter = dict()forkwinwords:? ? counter[kw] += 1
這樣寫(xiě)肯定會(huì)報(bào)錯(cuò)的,因?yàn)楦髟~的個(gè)數(shù)都沒(méi)有初始值,引發(fā)KeyError
2、改進(jìn)一下:加入if判斷
words = ['hello','world','nice','world']counter = dict()forkwinwords:ifkwinwords:? ? ? ? counter[kw] += 1else:? ? ? ? counter[kw] = 0
3、再改進(jìn):使用setdefault()方法設(shè)置默認(rèn)值
words = ['hello','world','nice','world']counter = dict()forkwinwords:? ? counter.setdefault(kw, 0)? ? counter[kw] += 1
setdefault(),需提供兩個(gè)參數(shù),第一個(gè)參數(shù)是鍵值,第二個(gè)參數(shù)是默認(rèn)值,每次調(diào)用都有一個(gè)返回值,如果字典中不存在該鍵則返回默認(rèn)值,如果存在該鍵則返回該值,利用返回值可再次修改代碼。
words = ['hello','world','nice','world']counter = dict()forkwinwords:? ? counter[kw] = counter.setdefault(kw, 0) + 1
4、接著改進(jìn)
一種特殊類型的字典本身就保存了默認(rèn)值defaultdict(),defaultdict類的初始化函數(shù)接受一個(gè)類型作為參數(shù),當(dāng)所訪問(wèn)的鍵不存在的時(shí)候,可以實(shí)例化一個(gè)值作為默認(rèn)值。
from collections import defaultdictdd = defaultdict(list)defaultdict(, {})#給它賦值,同時(shí)也是讀取dd['h'h]defaultdict(, {'hh': []})dd['hh'].append('haha')defaultdict(, {'hh': ['haha']})
該類除了接受類型名稱作為初始化函數(shù)的參數(shù)之外,還可以使用任何不帶參數(shù)的可調(diào)用函數(shù),到時(shí)該函數(shù)的返回結(jié)果作為默認(rèn)值,這樣使得默認(rèn)值的取值更加靈活。
>>> from collections import defaultdict>>>defzero():...? ? return0...>>> dd = defaultdict(zero)>>> dddefaultdict(, {})>>> dd['foo']0>>> dddefaultdict(, {'foo':0})
最終代碼:
fromcollectionsimportdefaultdictwords = ['hello','world','nice','world']#使用lambda來(lái)定義簡(jiǎn)單的函數(shù)counter = defaultdict(lambda:0)forkwinwords:? ? counter[kw] +=1
作者:FromNow
鏈接:http://www.lxweimin.com/p/26df28b3bfc8