【383】defaultdict 相关用法
可以定义一个字典,可以添加默认值,int 为 0,list 为 [],set 为 {}
int:默认值为 0
from collections import defaultdict
int_dict = defaultdict(int)
for i in range(5):
int_dict[i] += i
int_dict
output:
defaultdict(int, {0: 0, 1: 1, 2: 2, 3: 3, 4: 4})
list,默认值为空列表,也可以用 append
from collections import defaultdict
list_dict = defaultdict(list)
for i in range(5):
list_dict[i] += [i]
list_dict
output:
defaultdict(list, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})
set:默认值为空集合
from collections import defaultdict
int_dict = defaultdict(set)
for i in range(5):
int_dict[i].add(i)
int_dict
output:
defaultdict(set, {0: {0}, 1: {1}, 2: {2}, 3: {3}, 4: {4}})
浙公网安备 33010602011771号