dic = {}
产生异常内容
# print(dic['python'])
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[3], line 1 ----> 1 print(dic['python']) KeyError: 'python'
from collections import defaultdict
dic = defaultdict(int)
print(dic['python'])
0
lst = [1, 3, 4, 2, 1, 3, 5]
现在请写代码统计列表里各个值出现的次数,如果使用普通的 dict
类来实现,
代码可以这样写。
lst = [1, 3, 4, 2, 1, 3, 5]
count_dict = {}
for item in lst:
if item not in count_dict:
count_dict[item] = 0
count_dict[item] += 1
print(count_dict)
{1: 2, 3: 2, 4: 1, 2: 1, 5: 1}
使用 defaultdict
,则可以更加简洁一些,代码缩进更少。
from collections import defaultdict
lst = [1, 3, 4, 2, 1, 3, 5]
count_dict = defaultdict(int)
for item in lst:
count_dict[item] += 1
print(count_dict)
defaultdict(<class 'int'>, {1: 2, 3: 2, 4: 1, 2: 1, 5: 1})