defaultdict 的嵌套 defaultdict [英] Nested defaultdict of defaultdict
问题描述
有没有办法让 defaultdict 也成为 defaultdict 的默认值?(即无限级递归 defaultdict?)
Is there a way to make a defaultdict also be the default for the defaultdict? (i.e. infinite-level recursive defaultdict?)
我希望能够做到:
x = defaultdict(...stuff...)
x[0][1][0]
{}
所以,我可以做 x = defaultdict(defaultdict)
,但这只是第二级:
So, I can do x = defaultdict(defaultdict)
, but that's only a second level:
x[0]
{}
x[0][0]
KeyError: 0
有些食谱可以做到这一点.但是可以简单地使用普通的 defaultdict 参数来完成吗?
There are recipes that can do this. But can it be done simply just using the normal defaultdict arguments?
请注意,这是在询问如何进行无限级递归 defaultdict,因此它与 Python:defaultdict 的 defaultdict 不同?,这是如何做一个两级 defaultdict.
Note this is asking how to do an infinite-level recursive defaultdict, so it's distinct to Python: defaultdict of defaultdict?, which was how to do a two-level defaultdict.
我可能最终会使用 bunch 模式,但是当我意识到我不知道如何做到这一点时,这让我很感兴趣.
I'll probably just end up using the bunch pattern, but when I realized I didn't know how to do this, it got me interested.
推荐答案
对于任意数量的级别:
def rec_dd():
return defaultdict(rec_dd)
>>> x = rec_dd()
>>> x['a']['b']['c']['d']
defaultdict(<function rec_dd at 0x7f0dcef81500>, {})
>>> print json.dumps(x)
{"a": {"b": {"c": {"d": {}}}}}
当然,您也可以使用 lambda 来执行此操作,但我发现 lambda 的可读性较差.无论如何,它看起来像这样:
Of course you could also do this with a lambda, but I find lambdas to be less readable. In any case it would look like this:
rec_dd = lambda: defaultdict(rec_dd)
这篇关于defaultdict 的嵌套 defaultdict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!