为什么需要lambda嵌套defaultdict? [英] Why do you need lambda to nest defaultdict?
问题描述
对于为什么需要lambda函数来嵌套defaultdict感到有些困惑
I am a bit confused on why you need a lambda function for nesting defaultdict
你为什么不能这样呢?
test = defaultdict(defaultdict(list))
代替
test = defaultdict(lambda:defaultdict(float))
推荐答案
test = defaultdict(defaultdict(list))
因为defaultdict
要求您提供一些可以被称为 的名称,以创建缺少值的键. list
是可调用的,但defaultdict(list)
不是.这是一个defaultdict
实例,您不能调用defaultdict
.
Because defaultdict
requires that you give it something that can be called to create keys for missing values. list
is such a callable, but defaultdict(list)
is not. It's a defaultdict
instance, and you can't call a defaultdict
.
lambda
是一个函数,调用该函数时,返回一个可以在字典中使用的值,因此它可以正常工作.
The lambda
is a function that, when called, returns a value that can be used in the dictionary, so it works.
实质上,defaultdict(list)
将在实例化defaultdict
之前的 中进行评估,并且您想推迟直到遇到丢失的键.这就是为什么在这里使用可调用对象(类型或函数)的原因.
Essentially, defaultdict(list)
is going to be evaluated before your defaultdict
is instantiated, and you want to defer that until a missing key is encountered. This is why a callable object (a type or a function) is used here.
这篇关于为什么需要lambda嵌套defaultdict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!