Python Lambda理解印刷I

发布于 2025-01-27 08:25:10 字数 244 浏览 2 评论 0原文

我正在尝试使用综合来编写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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

勿忘初心 2025-02-03 08:25:10

您需要确保对i进行评估并在lambda被定义的lambda的主体内部绑定,而不是将其延迟到 /em>(在此期间,循环完成了,i = 9)。一种方法是将i用作lambda参数的默认值,因为在定义函数而不是称为函数时评估默认

>>> funcs = [lambda x=i: print(x) for i in range(10)]
>>> funcs[0]()
0
>>> funcs[1]()
1

值需要使用其他变量名称;您可以命名参数i,它将在lambda主体内部遮蔽,并且仍然以相同的方式工作:

>>> funcs = [lambda i=i: print(i) for i in range(10)]

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 and i = 9). One way of doing that is to use i 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:

>>> funcs = [lambda x=i: print(x) for i in range(10)]
>>> funcs[0]()
0
>>> funcs[1]()
1

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:

>>> funcs = [lambda i=i: print(i) for i in range(10)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文