python学习-defaultdict
生活随笔
收集整理的這篇文章主要介紹了
python学习-defaultdict
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 傳統(tǒng)字典使用
- 使用setdefault
- 使用defaultdict
傳統(tǒng)字典使用
統(tǒng)計某個單詞出現(xiàn)次數(shù)
lst1 = ['這', '是', '一', '段', '話', '一', '段', '話'] rst = dict() for word in lst1:if word not in rst:rst[word] = 1else:rst[word] += 1print('rst = ', rst)
這是傳統(tǒng)方法。
使用setdefault
for word in lst1:rst.setdefault(word, 0)rst[word] += 1print('rst = ', rst)給沒有向字典里面添加的key設(shè)為0。
使用defaultdict
from collections import defaultdict rst1 = defaultdict(int) for word in lst1:rst1[word] += 1 print('rst = ', rst1)因為defaultdict(int)的參數(shù)是int,所以如果添加不存在的key,value會默認給0;
另一種使用方式:
設(shè)置了默認值以后,添加不存在的key,可以使用預(yù)設(shè)的值返回。這樣就能實現(xiàn)一些復(fù)雜的字典。
這里定義了dictVal函數(shù),給dict設(shè)置默認值是dictVal函數(shù)的返回值。
所以運行結(jié)果:
總結(jié)
以上是生活随笔為你收集整理的python学习-defaultdict的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 轮值董事长徐直军:华为已基本实现 14n
- 下一篇: 酷狗音乐状态栏歌词怎么关闭