这个python函数中的lambda表达式发生了什么?

Dav*_*vid 5 python lambda

为什么尝试创建curried函数列表不起作用?

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
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

实际上我希望上述函数执行的功能是:

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
Run Code Online (Sandbox Code Playgroud)

a p*_*erd 12

在Python中,在循环和分支中创建的变量不是作用域.您正在创建的所有函数lambda都引用了相同的i变量,该变量9在循环的最后一次迭代中设置.

解决方案是创建一个返回函数的函数,从而确定迭代器变量的范围.这就是这种functools.partial()方法的原因.例如:

def test():
    def makefunc(i):
        return lambda x: p(i, x)
    a = []
    for i in range(10):
        a.append(makefunc(i))
    return a
Run Code Online (Sandbox Code Playgroud)