这个python函数中的lambda表达式是怎么回事? [英] What's going on with the lambda expression in this python function?
问题描述
为什么这种尝试创建咖喱函数列表的方法不起作用?
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
这是怎么回事?
实际上可以实现上述功能的功能是:
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
推荐答案
在Python中,在循环和分支中创建的变量没有作用域.您使用lambda
创建的所有函数均引用相同的i
变量,该变量在循环的最后一次迭代时设置为9
.
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 same i
variable, which is set to 9
on the last iteration of the loop.
解决方案是创建一个函数,该函数返回一个函数,从而确定迭代器变量的范围.这就是functools.partial()
方法起作用的原因.例如:
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:
def test():
def makefunc(i):
return lambda x: p(i, x)
a = []
for i in range(10):
a.append(makefunc(i))
return a
这篇关于这个python函数中的lambda表达式是怎么回事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!