Python的Lambda迭代无法正常工作 [英] Python's lambda iteration not working as intended

查看:73
本文介绍了Python的Lambda迭代无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我打算有两个按钮,当每个按钮按下时,分别将'0'和'1'打印到stdout.但是,当程序运行时,它们都打印"1",这是我在for迭代中拥有的最后一个值.为什么?

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()

推荐答案

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 the i 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:

for i in range(0,2):
    cmd = lambda i=i: sys.stdout.write(str(i))
    tk.Button(text="print '%d'" % i,command=cmd).pack()

这篇关于Python的Lambda迭代无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆