Python create function in a loop capturing the loop variable

后端 未结 5 1405
無奈伤痛
無奈伤痛 2020-12-05 03:38

What\'s going on here? I\'m trying to create a list of functions:

def f(a,b):
    return a*b

funcs = []

for i in range(0,10):
    funcs.append(lambda x:f(         


        
5条回答
  •  情歌与酒
    2020-12-05 04:07

    There's only one i which is bound to each lambda, contrary to what you think. This is a common mistake.

    One way to get what you want is:

    for i in range(0,10):
        funcs.append(lambda x, i=i: f(i, x))
    

    Now you're creating a default parameter i in each lambda closure and binding to it the current value of the looping variable i.

提交回复
热议问题