defaultdict defaultdict? [英] defaultdict of defaultdict?

查看:82
本文介绍了defaultdict 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 需要临时构建,具体取决于 xa xb 元素。

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

但后来我将无法使用:

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).

如果您尝试从最后一个默认值访问密钥,即 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆