You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于collections.defaultdict(set)的结构类型及自定义默认集合的技术咨询

问题1:collections.defaultdict(set)创建的是什么类型的数据结构?

它是Python标准库collections模块下的带默认值的字典子类(defaultdict实例)。和普通字典的核心区别是:当访问不存在的键时,它会自动调用传入的工厂函数(此处为set)生成对应键的默认值——也就是一个空集合,不会抛出KeyError异常。

示例代码:

from collections import defaultdict
d = defaultdict(set)
d['sports'].add('football')  # 无需提前初始化键对应的集合,直接调用集合方法
print(d['sports'])  # 输出: {'football'}
问题2:当前我们使用set作为缺失值的默认值,如何使用未定义的集合来实现这一目的?

这里的“未定义的集合”指自定义集合类(非Python内置set),只需将自定义集合类作为defaultdict的工厂参数传入即可。

示例1:自定义具名集合类

from collections import defaultdict

# 定义自定义集合类,可添加自定义属性或方法
class CustomSet(set):
    def __init__(self):
        super().__init__()
        self.tag = "custom_collection"

# 传入自定义集合类作为默认工厂
d = defaultdict(CustomSet)
d['my_collection'].add('example')
print(d['my_collection'])  # 输出: {'example'}
print(d['my_collection'].tag)  # 输出: custom_collection

示例2:动态创建匿名集合类

如果需要完全未提前定义的匿名集合类,可以用type动态生成:

from collections import defaultdict

# 动态生成继承自set的匿名类
AnonymousSet = type('AnonymousSet', (set,), {'custom_attr': 'anonymous'})
d = defaultdict(AnonymousSet)
d['anon_set'].add('item')
print(d['anon_set'])  # 输出: {'item'}
print(d['anon_set'].custom_attr)  # 输出: anonymous

内容的提问来源于stack exchange,提问作者Devansh Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 18:18:06