python 中defaultdict()对字典进行初始化的用法介绍

Hellens ·
更新时间:2024-09-20
· 1297 次阅读

目录

用法讲解:

1. 不使用defaultdict(): 

2. 使用defaultdict(): 

用法讲解:

一般情况下,在使用字典时,先定义一个空字典(如dict_a = {}),然后往字典中添加元素只需要 dict_a[key] = value即可。读取字典中的元素时同理,但前提时字典中存在这个key,否则就会报错。

defaultdict()的作用在于,即使字典中的key不存在,在查找时也会对它的value赋予一个默认值,从而避免了报错。

具体来说,defaultdict接受一个工厂函数作为参数,如下来构造:

dict =defaultdict(factory_function)

这个factory_function可以是list、set、str等等,作用是当key不存在时,返回的是工厂函数的默认值,比如list对应[ ],str对应的是空字符串,set对应set( ),int对应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]=[

应用举例: 题目描述:

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 

到此这篇关于python 中defaultdict()对字典进行初始化的文章就介绍到这了,更多相关python defaultdict()初始化内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



字典 Python 初始化

需要 登录 后方可回复, 如果你还没有账号请 注册新账号