简体   繁体   English

defaultdict(lambda:defaultdict(dict))的含义

[英]Meaning of defaultdict(lambda: defaultdict(dict))

Python中以下行的含义是什么?

x = defaultdict(lambda: defaultdict(dict))

Let's resolve it from the inside out. 让我们从内而外解决它。 Firstly, dict is the dictionary type. 首先, dict是字典类型。 Like other types, calling it creates an instance (also known as object) of that type. 与其他类型一样,调用它会创建该类型的实例(也称为对象)。 A defaultdict is a type that takes a callable parameter: something that, when called, produces an item to put in the dictionary. defaultdict是一种带有可调用参数的类型:被调用时会产生要放入字典的项目。 This happens when an entry is accessed that was not present, instead of producing a KeyError like an ordinary dict . 当访问的条目不存在时发生这种情况,而不是像普通dict那样产生KeyError Thirdly, lambda is a way to create unnamed functions based on a single expression, so these two are similar (the second holds a function that knows its own name, the first doesn't): 第三, lambda是一种基于单个表达式创建未命名函数的方法,因此这两个是相似的(第二个函数拥有一个知道自己名称的函数,第一个不知道):

y = lambda: defaultdict(dict)

def y():
    return defaultdict(dict)

And finally the whole thing is wrapped in another defaultdict . 最后,整个事情都包装在另一个defaultdict So the result is that x is a defaultdict that produces defaultdict s that produce dict instances. 因此,结果是x是一个defaultdict ,该defaultdict生成defaultdict ,该defaultdict生成dict实例。 At the third level there aren't defaults anymore. 在第三级,没有默认值了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM