一、defaultdict是什么?
defaultdict 是python自带的一种特殊字典类型,允许我们为字典中的键提供一个 默认值。
与普通的 dict 不同,在使用 defaultdict 时,如果访问的键不存在,它会自动创建该键并将默认值赋给它。 这在某些场景下非常方便,尤其是处理集合或列表时,无需手动检查 键是否存在。
二、使用步骤
1.引入
代码如下(示例):
from collections import defaultdict
# 使用 list 作为默认值
dict = defaultdict(list)
# 使用 int 作为默认值
dict = defaultdict(int)
# 使用 set 作为默认值
dict = defaultdict(set)
2.读入数据
代码如下(示例):
# list
from collections import defaultdict
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
dict = defaultdict(list) # 以list为默认value
for key, value in s: # 保存每个颜色中的数字
dict[key].append(value)
print(dict.items())
# [('yellow', [1, 3]), ('blue', [2, 4]), ('red', [1])]
# int
s = 'IwillACmore'
dict = defaultdict(int) # 以int为默认value
for key in s: # 每个字符初始个数为0,无需判断key是否在字典中
dict[key] += 1
print(dict.items())
# [('I', 1), ('w', 1), ('i', 1), ('l', 2), ('A', 1), ('C', 1), ('m', 1), ('o', 1), ('r', 1), ('e', 1)]
# set
s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
dict = defaultdict(set) # 以set为默认value
for key, value in s:
dict[key].add(value)
print(dict.items())
# [('red', {1, 3}), ('blue', {2, 4})]
三、题目练习
A 万年沉睡的宝藏
https://ac.nowcoder.com/acm/contest/100007/A 可进去查看示例
思路分析:
op1 : 将一个元素插入到 set ;
op2 : 求出 set 中元素的数量;
op3 : 判断元素是否在 set 中;
op4 : 求出 dict 中的元素数量
题解代码:
from collections import defaultdict
dict = defaultdict(set)
q = int(input())
for _ in range(q):
res = input().split()
if res[0] == '1':
dict[res[1]].add(res[2])
if res[0] == '2':
if res[1] not in dict:
print(0)
else:
print(len(dict[res[1]]))
if res[0] == '3':
if res[1] not in dict or res[2] not in dict[res[1]]:
print(0)
else:
print(1)
if res[0] == '4':
print(len(dict))