本文介绍了Python在捕获循环变量的循环中创建函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是怎么回事?我正在尝试创建一个函数列表:
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 中的 lambdas 是闭包......你给它的参数在 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在捕获循环变量的循环中创建函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!