Python 中的 defaultdict 数据类型
首先,defaultdict 是 dict 的一个子类。通常 Python 中字典(dict)是通过键值对来存取的,当索引一个不存在的键时,就会引发 keyerror 异常。那么,defaultdict 就可以解决这个问题,它可以实现为不存的键值返回一个默认值。
defaultdict是 collections 包下的一个模块,defaultdict 在初始化时可以提供一个 default_factory 的参数,default_factory 接收一个工厂函数作为参数, 可以是 int、str、list 等内置函数,也可以是自定义函数。
001、
>>> str1 = "aaabcdddddeffggg" ## 测试字符串 >>> dict1 = {} ## 标准字典 >>> for i in str1: ... dict1[i] += 1 ## 标准字典无法直接统计字母的个数 ... Traceback (most recent call last): File "<stdin>", line 2, in <module> KeyError: 'a' >>> from collections import defaultdict ## 从collections模块中导入defaultdict函数 >>> dict2 = defaultdict(int) ## 为不存在的键值返回一个默认值 >>> for j in str1: ... dict2[j] += 1 ... >>> dict2 ## 结果文件 defaultdict(<class 'int'>, {'a': 3, 'b': 1, 'c': 1, 'd': 5, 'e': 1, 'f': 2, 'g': 3}) >>> for i,j in dict2.items(): ... print(i,j) ... a 3 b 1 c 1 d 5 e 1 f 2 g 3
参考:https://blog.csdn.net/weixin_36383252/article/details/114910657
分类:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2020-11-15 ansible