使用 lambdas 进行 Python 列表理解 [英] Python list comprehension with lambdas
问题描述
我正在运行 Python 3.4.2,但我对代码的行为感到困惑.我正在尝试创建一个递增程度的可调用多项式函数列表:
I'm running Python 3.4.2, and I'm confused at the behavior of my code. I'm trying to create a list of callable polynomial functions with increasing degree:
bases = [lambda x: x**i for i in range(3)]
但出于某种原因,它会这样做:
But for some reason it does this:
print([b(5) for b in bases])
# [25, 25, 25]
为什么 bases
在列表推导式中似乎是重复的最后一个 lambda 表达式的列表?
Why is bases
seemingly a list of the last lambda expression, in the list comprehension, repeated?
推荐答案
问题,这是一个经典陷阱",是在 lambda 函数中引用的 i
是 直到这lambda 函数被称为.那个时候i
的值就是它的最后一个值for-loop
结束时绑定到,即 2
.
The problem, which is a classic
"gotcha", is
that the i
referenced in the lambda functions is not looked up until the
lambda function is called. At that time, the value of i
is the last value it
was bound to when the for-loop
ended, i.e. 2
.
如果将 i
绑定到 lambda
函数定义中的默认值,则每个 i
都成为局部变量,并且它的默认值在 lambda 被定义而不是被调用时被评估并绑定到函数.
If you bind i
to a default value in the definition of the lambda
functions, then each i
becomes a local variable, and its default value is evaluated and bound to the function at the time the lambda is defined rather than called.
因此,当 lambda 被调用时,i
现在会在 本地范围 中查找,并使用其默认值:
Thus, when the lambda is called, i
is now looked up in the local scope, and its default value is used:
In [177]: bases = [lambda x, i=i: x**i for i in range(3)]
In [178]: print([b(5) for b in bases])
[1, 5, 25]
供参考:
这篇关于使用 lambdas 进行 Python 列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!