Python 的 lambda 迭代未按预期工作
在下面的代码中,我打算有两个按钮,当按下每个按钮时,“0”和“1”将分别打印到标准输出。然而,当程序运行时,它们都打印“1”,这是我在 for 迭代中得到的最后一个值。为什么?
import Tkinter as tk
import sys
root = tk.Tk()
for i in range(0,2):
cmd = lambda: sys.stdout.write(str(i))
tk.Button(text="print '%d'" % i,command=cmd).pack()
root.mainloop()
In the code below I intend to have two buttons, and when each is pressed '0' and '1' are to be printed to stdout, respectively. However when the program is run, they both print '1', which is the last value i had in the for iteration. Why?
import Tkinter as tk
import sys
root = tk.Tk()
for i in range(0,2):
cmd = lambda: sys.stdout.write(str(i))
tk.Button(text="print '%d'" % i,command=cmd).pack()
root.mainloop()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您创建它时,
i
并未在 lambda 中捕获(如您所愿)。相反,这两个函数都会引用外部 for 循环中的i
,该循环在函数创建之后和运行之前会发生变化。要捕获它,您可以使用默认值:The
i
is not captured in the lambda when you create it (as you wanted). Instead, both functions refer back to thei
in the external for loop, which changes after the function is created and before it is run. To capture it, you can use a default value:中的问题
这肯定是On lambdas、capture 和 mutability
一遍又一遍地出现......
Surely it's the issue in
On lambdas, capture, and mutability
that comes up over and over...
我认为使用匿名函数只是为了给它命名有点奇怪。为什么不这样写呢?
I think it's a bit odd to use an anonymous function just to then give it a name. Why not write it like this?