【数据结构】默认字典defaultdict的介绍与应用 python

一、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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值