python?中defaultdict()對(duì)字典進(jìn)行初始化的用法介紹
用法講解:
- 一般情況下,在使用字典時(shí),先定義一個(gè)空字典(如dict_a = {}),然后往字典中添加元素只需要 dict_a[key] = value即可。讀取字典中的元素時(shí)同理,但前提時(shí)字典中存在這個(gè)key,否則就會(huì)報(bào)錯(cuò)。
- 而defaultdict()的作用在于,即使字典中的key不存在,在查找時(shí)也會(huì)對(duì)它的value賦予一個(gè)默認(rèn)值,從而避免了報(bào)錯(cuò)。
- 具體來(lái)說(shuō),defaultdict接受一個(gè)工廠函數(shù)作為參數(shù),如下來(lái)構(gòu)造:
dict =defaultdict(factory_function)
- 這個(gè)factory_function可以是list、set、str等等,作用是當(dāng)key不存在時(shí),返回的是工廠函數(shù)的默認(rèn)值,比如list對(duì)應(yīng)[ ],str對(duì)應(yīng)的是空字符串,set對(duì)應(yīng)set( ),int對(duì)應(yīng)0。
from collections import defaultdict dict1 = defaultdict(int) # dict1[1]=0 dict2 = defaultdict(set) # dict2[1]=set() dict3 = defaultdict(str) # dict3[1]= dict4 = defaultdict(list) # dict4[1]=[
應(yīng)用舉例: 題目描述:
1. 不使用defaultdict():
def isAnagram(s, t): """ :type s: str :type t: str :rtype: bool """ dict_s = {} for item in s: if item not in dict_s.keys(): dict_s[item] = 1 else: dict_s[item] += 1 dict_t = {} for item in t: if item not in dict_t.keys(): dict_t[item] = 1 else: dict_t[item] += 1 return dict_s == dict_t
2. 使用defaultdict():
def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ from collections import defaultdict dict_s = defaultdict(int) dict_t = defaultdict(int) for item in s: dict_s[item] += 1 for item in t: dict_t[item] += 1 return dict_s == dict_t
參考:https://www.jianshu.com/p/bbd258f99fd3
到此這篇關(guān)于python 中defaultdict()對(duì)字典進(jìn)行初始化的文章就介紹到這了,更多相關(guān)python defaultdict()初始化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 網(wǎng)頁(yè)解析HTMLParse的實(shí)例詳解
這篇文章主要介紹了Python 網(wǎng)頁(yè)解析HTMLParse的實(shí)例詳解的相關(guān)資料,python里提供了一個(gè)簡(jiǎn)單的解析模塊HTMLParser類,使用起來(lái)也是比較簡(jiǎn)單的,解析語(yǔ)法沒(méi)有用到XPath類似的簡(jiǎn)潔模式,需要的朋友可以參考下2017-08-08Python中的類型提示(Type Hints)總結(jié)
Python3.5 版本引入了類型提示(Type Hints),它允許開(kāi)發(fā)者在代碼中顯式地聲明變量、函數(shù)、方法等的類型信息,下面小編就來(lái)帶大家一起看看Python類型提示的初步使用吧2023-05-05python飛機(jī)大戰(zhàn)pygame碰撞檢測(cè)實(shí)現(xiàn)方法分析
這篇文章主要介紹了python飛機(jī)大戰(zhàn)pygame碰撞檢測(cè)實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Python使用pygame實(shí)現(xiàn)飛機(jī)大戰(zhàn)游戲中碰撞檢測(cè)的原理與相關(guān)操作技巧,需要的朋友可以參考下2019-12-12基于python,Matplotlib繪制函數(shù)的等高線與三維圖像
這篇文章主要介紹了基于python,Matplotlib繪制函數(shù)的等高線與三維圖像,函數(shù)的等高線及其三維圖像的可視化方法,下面一起來(lái)學(xué)習(xí)具體內(nèi)容吧,需要的小伙伴可以參考一下2022-01-01python pycurl驗(yàn)證basic和digest認(rèn)證的方法
這篇文章主要介紹了python pycurl驗(yàn)證basic和digest認(rèn)證的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-05-05