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