循环中的Python create function捕获循环变量 [英] Python create function in a loop capturing the loop variable
本文介绍了循环中的Python create function捕获循环变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是怎么回事?我正在尝试创建功能列表:
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(i,x))
这没有达到我的期望.我希望列表像这样:
This isn't doing what I expect. I would expect the list to act like this:
funcs[3](3) = 9
funcs[0](5) = 0
但是列表中的所有功能似乎都是相同的,并且将固定值设置为9:
But all the functions in the list seem to be identical, and be setting the fixed value to be 9:
funcs[3](3) = 27
funcs[3](1) = 9
funcs[2](6) = 54
有什么想法吗?
推荐答案
python中的lambda是闭包....您给它提供的参数在lambda被评估之前不会被评估.那时,无论如何,i = 9,因为您的迭代已完成.
lambdas in python are closures.... the arguments you give it aren't going to be evaluated until the lambda is evaluated. At that time, i=9 regardless, because your iteration is finished.
您正在寻找的行为可以通过functools.partial
The behavior you're looking for can be achieved with functools.partial
import functools
def f(a,b):
return a*b
funcs = []
for i in range(0,10):
funcs.append(functools.partial(f,i))
这篇关于循环中的Python create function捕获循环变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文