defaultdict 的 defaultdict? [英] defaultdict of defaultdict?
问题描述
有没有办法使用 defaultdict(defaultdict(int))
来使下面的代码工作?
Is there a way to have a defaultdict(defaultdict(int))
in order to make the following code work?
for x in stuff:
d[x.a][x.b] += x.c_int
d
需要临时构建,具体取决于 x.a
和 x.b
元素.
d
needs to be built ad-hoc, depending on x.a
and x.b
elements.
我可以使用:
for x in stuff:
d[x.a,x.b] += x.c_int
但是那样我就不能使用了:
but then I wouldn't be able to use:
d.keys()
d[x.a].keys()
推荐答案
是这样的:
defaultdict(lambda: defaultdict(int))
当您尝试访问不存在的密钥时,将调用 defaultdict
(在本例中为 lambda: defaultdict(int)
)的参数.它的返回值将被设置为这个键的新值,这意味着在我们的例子中 d[Key_doesnt_exist]
的值将是 defaultdict(int)
.
The argument of a defaultdict
(in this case is lambda: defaultdict(int)
) will be called when you try to access a key that doesn't exist. The return value of it will be set as the new value of this key, which means in our case the value of d[Key_doesnt_exist]
will be defaultdict(int)
.
如果你试图访问最后一个 defaultdict 中的一个键,即 d[Key_doesnt_exist][Key_doesnt_exist]
它将返回 0,这是最后一个 defaultdict 的参数的返回值,即 int()
.
If you try to access a key from this last defaultdict i.e. d[Key_doesnt_exist][Key_doesnt_exist]
it will return 0, which is the return value of the argument of the last defaultdict i.e. int()
.
这篇关于defaultdict 的 defaultdict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!