这个 python 函数中的 lambda 表达式是怎么回事?
为什么创建柯里化函数列表的尝试不起作用?
def p(x, num):
print x, num
def test():
a = []
for i in range(10):
a.append(lambda x: p (i, x))
return a
>>> myList = test()
>>> test[0]('test')
9 test
>>> test[5]('test')
9 test
>>> test[9]('test')
9 test
这里发生了什么?
实际上执行我期望上述函数执行的操作的函数是:
import functools
def test2():
a = []
for i in range (10):
a.append(functools.partial(p, i))
return a
>>> a[0]('test')
0 test
>>> a[5]('test')
5 test
>>> a[9]('test')
9 test
Why does this attempt at creating a list of curried functions not work?
def p(x, num):
print x, num
def test():
a = []
for i in range(10):
a.append(lambda x: p (i, x))
return a
>>> myList = test()
>>> test[0]('test')
9 test
>>> test[5]('test')
9 test
>>> test[9]('test')
9 test
What's going on here?
A function that actually does what I expect the above function to do is:
import functools
def test2():
a = []
for i in range (10):
a.append(functools.partial(p, i))
return a
>>> a[0]('test')
0 test
>>> a[5]('test')
5 test
>>> a[9]('test')
9 test
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Python 中,在循环和分支中创建的变量没有作用域。 您使用
lambda
创建的所有函数都引用同一个i
变量,该变量在最后一次迭代中设置为9
循环。解决方案是创建一个返回函数的函数,从而确定迭代器变量的范围。 这就是 functools.partial() 方法起作用的原因。 例如:
In Python, variables created in loops and branches aren't scoped. All of the functions you're creating with
lambda
have a reference to the samei
variable, which is set to9
on the last iteration of the loop.The solution is to create a function which returns a function, thus scoping the iterator variable. This is why the
functools.partial()
approach works. For example:好吧,你也可以将 i 绑定到一个懒惰的外部 lambda 上。
Well you can also bind the i to an outer lambda for the lazy.
我总是很困惑为什么这不起作用。 感谢您的解释,“付费书呆子”。 我个人更喜欢这个解决方案:
注意 lambda 的 val_i=i 默认参数,它能够在循环期间捕获
i
的瞬时值,同时仍然有效地使 lambda 成为 1 个变量的函数。 (顺便说一句:将您的x
更改为num
以匹配p
的定义。)我更喜欢它,因为:刚刚进行了搜索并找到了针对同一问题的更详细解释那里: python lambda 函数及其参数的范围
I was always confused as to why this doesn't work. Thanks for the explanation, 'a paid nerd'. I personally prefer this solution:
Note the
val_i=i
default argument of thelambda
that enables to capture the instantaneous value ofi
during the loop whilst still effectively makinglambda
a function of 1 variable. (BTW: changed yourx
intonum
to matchp
's definition.) I like it better because:functools
Just did a search and found more detailed explanations for the same problem there: Scope of python lambda functions and their parameters
我问过类似的问题,得到了两个答案。 一个与此处接受的答案基本相同,另一个不太清楚但稍微简洁一些。
在 Tkinter 中动态创建菜单。 (lambda 表达式?)
I asked a similar question, and got two answers. One basically the same as the accepted answer here, and the other which is less clear but slightly more succint.
Dynamically creating a menu in Tkinter. (lambda expressions?)