Python Lambda和作用域 [英] Python lambdas and scoping
本文介绍了Python Lambda和作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下代码段:
funcs = []
for x in range(3):
funcs.append(lambda: x)
print [f() for f in funcs]
我希望它会打印[0, 1, 2]
,但是会打印[2, 2, 2]
.关于lambda如何与作用域一起工作,我是否缺少一些基本的知识?
I would expect it to print [0, 1, 2]
, but instead it prints [2, 2, 2]
. Is there something fundamental I'm missing about how lambdas work with scope?
推荐答案
这是Python中的常见问题.基本上,作用域是这样的:调用f()
时,它将使用x
的当前值,而不是形成lambda时的x
值.有一个标准的解决方法:
This is a frequent question in Python. Basically the scoping is such that when f()
is called, it will use the current value of x
, not the value of x
at the time the lambda is formed. There is a standard workaround:
funcs = []
for x in range(10):
funcs.append(lambda x=x: x)
print [f() for f in funcs]
使用lambda x = x
检索并保存x
的当前值.
The use of lambda x = x
retrieves and saves the current value of x
.
这篇关于Python Lambda和作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文