python 中 collections 模块中的 defaultdict
01、
[root@pc1 test1]# python3 Python 3.11.4 (main, Jul 5 2023, 14:15:25) [GCC 11.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from collections import defaultdict ## 引入该模块 >>> dict1 = defaultdict(int) ## 生成数字字典 >>> dict2 = dict() >>> dict1 defaultdict(<class 'int'>, {}) >>> dict2 {} >>> dict1["aa"] += 5 ## 默认数字字典可以直接进行数值运算 >>> dict1 defaultdict(<class 'int'>, {'aa': 5}) >>> dict2["aa"] += 5 ## 一般字典不可以 Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'aa' >>> dict2 {}

。

浙公网安备 33010602011771号