[英]Building a defaultdict whose values are defaultdict
Is there any particular reason that my application says the argument must be callable or none type? 我的应用程序说该参数必须是可调用的还是没有类型,是否有任何特殊原因? I'm pretty sure this is how you'd instantiate a defaultdict with a defaultdict as its values.
我很确定这是您如何使用defaultdict作为其值实例化defaultdict的方法。
dict = defaultdict(defaultdict(set))
The argument provided to the defaultdict
constructor must be a zero-argument callable (see the docs ), so defaultdict(defaultdict)
does work, but defaultdict(defaultdict(set))
does not. 提供给
defaultdict
构造函数的参数必须是可调用零参数的参数(请参见docs ),因此defaultdict(defaultdict)
可以工作,而defaultdict(defaultdict(set))
不能。 You can 'cheat' a little though: 不过,您可以“作弊”一点:
d = defaultdict(lambda: defaultdict(set))
That way you provide a zero-argument callable in the form of the lambda
function which in turn, when called, returns the appropriate default value you want. 这样,您就可以以
lambda
函数的形式提供零参数可调用对象,该函数又会在被调用时返回所需的默认值。
You need to provide a function for defaultdict
constructor but defauldict(set)
is defaultdict
object instead. 您需要为
defaultdict
构造函数提供一个函数,但defauldict(set)
是defaultdict
对象。 If you want to build a defaultdict
whose values are defaultdicts
you can use lambdas: 如果您要构建一个
defaultdict
其值为defaultdicts
,则可以使用lambda:
from collections import defaultdict
dd = lambda: defaultdict(dd)
x = dd()
x['foo']['bar']['foobar'] = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.