Python Lambda理解印刷I
我正在尝试使用综合来编写lambdas的列表,其中每个lambda都会打印在列表中的位置的索引。
list = [lambda : print(i) for i in range(10)]
list[0]()
但是问题在于,呼叫任何lambdas都会产生相同的结果,它们打印9。我如何以每个lambda打算以我打算的方式捕获我的价值?
I'm trying to use comprehensions to write a list of lambdas, where each lambda when called will print the index that is it's position in the list.
list = [lambda : print(i) for i in range(10)]
list[0]()
But the problem is that calling any of the lambdas all produce the same result, they print 9. How can I capture the value of i in the way I intend to for each lambda?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要确保对
i
进行评估并在lambda被定义的lambda的主体内部绑定,而不是将其延迟到 /em>(在此期间,循环完成了,i = 9
)。一种方法是将i
用作lambda参数的默认值,因为在定义函数而不是称为函数时评估默认值需要使用其他变量名称;您可以命名参数
i
,它将在lambda主体内部遮蔽,并且仍然以相同的方式工作:You need to make sure that
i
is evaluated and bound inside the body of the lambda at the time the lambda is defined, rather than delaying it until it's called (by which time the loop has finished andi = 9
). One way of doing that is to usei
as the default value of a parameter to the lambda, since the default is evaluated when the function is defined rather than when it's called:Note that you don't actually need to use a different variable name; you can name the parameter
i
and it will be shadowed inside the lambda body and still work the same way: