带有lambda函数的字典理解给出错误的结果 [英] Dictionary comprehension with lambda functions gives wrong results
问题描述
我在Python 3.5.1中尝试了以下代码:
I tried the following code in Python 3.5.1:
>>> f = {x: (lambda y: x) for x in range(10)}
>>> f[5](3)
9
很明显,这应该返回5
.我不知道其他值来自何处,也找不到任何东西.
It's obvious that this should return 5
. I don't understand where the other value comes from, and I wasn't able to find anything.
似乎与引用有关-它总是返回f[9]
的答案,这是最后分配的功能.
It seems like it's something related to reference - it always returns the answer of f[9]
, which is the last function assigned.
这是什么错误,应该如何做才能使其正常工作?
What's the error here, and how should this be done so that it works properly?
推荐答案
Python作用域是词汇性的.闭包将引用变量的名称和范围,而不是变量的实际对象/值.
Python scoping is lexical. A closure will refer to the name and scope of the variable, not the actual object/value of the variable.
发生的情况是每个lambda都捕获变量x
不是值x
.
What happens is that each lambda is capturing the variable x
not the value of x
.
在循环结束时,变量x
绑定到9,因此每个lambda都将引用该值为9的x
.
At the end of the loop the variable x
is bound to 9, therefore every lambda will refer to this x
whose value is 9.
为什么@ChrisP的答案有效:
Why @ChrisP's answer works:
make_func
强制评估x
的值(传递时) 转化为功能).因此,lambda的当前值为x
并且避免了上述范围界定问题.
make_func
forces the value ofx
to be evaluated (as it is passed into a function). Thus, the lambda is made with value ofx
currently and we avoid the above scoping issue.
def make_func(x):
return lambda y: x
f = {x: make_func(x) for x in range(10)}
这篇关于带有lambda函数的字典理解给出错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!