Python lambda 不记得 for 循环中的参数 [英] Python lambda doesn't remember argument in for loop

查看:42
本文介绍了Python lambda 不记得 for 循环中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
在 lambda 表达式中使用变量的值

我正在使用 python 并尝试隔离我在 lambda 函数中遇到的问题.

I'm working with python and trying to isolate a problem I had with lambda functions.

从下面的代码中,我希望创建两个 lambda 函数,每个函数都得到不同的 x,输出应该是
12

From the following code I was expecting to create two lambda functions, each getting a different x, and the output should be
1 2

但输出是22

为什么?我怎样才能做出两个不同的功能?使用 def?

Why? And how can I make two different functions? Using def?

def main():
    d = {}
    for x in [1,2]:
        d[x] = lambda : print(x)

    d[1]()
    d[2]()


if __name__ == '__main__':
    main()

推荐答案

代码中 lambda 的主体引用名称 x.与该名称关联的值在循环的下一次迭代中发生更改,因此当 lambda 被调用并解析名称时,它会获得新值.

The body of the lambda in your code references the name x. The value associated with that name is changed on the next iteration of the loop, so when the lambda is called and it resolves the name it obtains the new value.

为了达到你预期的结果,将循环中x的值绑定到lambda的一个参数上,然后引用那个参数,如下图:

To achieve the result you expected, bind the value of x in the loop to a parameter of the lambda and then reference that parameter, as shown below:

def main():
    d = {}
    for x in [1,2]:
        d[x] = lambda x=x: print(x)

    d[1]()
    d[2]()


if __name__ == '__main__':
    main()

>>> 
1
2

这篇关于Python lambda 不记得 for 循环中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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