本文介绍了在循环内创建 lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
Python 中的 (lambda) 函数闭包捕获什么?
lambda 函数不关闭 Python 中的参数?
我正在尝试在迭代对象列表的循环中创建 lambda:
I am trying to create lambdas inside a loop that iterates over a list of objects:
lambdas_list = []
for obj in obj_list:
lambdas_list.append(lambda : obj.some_var)
现在,如果我遍历 lambdas 列表并像这样调用它们:
Now, if I iterate over the lambdas list and call them like this:
for f in lambdas_list:
print f()
我得到相同的值.这是 obj_list
中最后一个 obj
的值,因为它是列表迭代器块中的最后一个变量.有什么想法可以很好地(pythonic)重写代码以使其工作?
I get the same value. That is the value of the last obj
in obj_list
since that was the last variable in the block of the list iterator. Any ideas fn a good (pythonic) rewrite of the code to make it work?
推荐答案
改用这一行:
lambdas_list.append(lambda obj=obj: obj.some_var)
这篇关于在循环内创建 lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!