What's going on with the lambda expression in this python function?

前端 未结 4 1447
甜味超标
甜味超标 2020-12-19 11:53

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):
             


        
4条回答
  •  鱼传尺愫
    2020-12-19 12:00

    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.

    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
    

提交回复
热议问题