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

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

问题描述


可能存在重复:


我正在使用python,并试图找出与lambda函数有关的问题。

从以下代码中,我期望创建两个lambda函数,每个函数都获得一个不同的x,输出应该是
1
2

但输出是
2
2

为什么?
我该如何做两个不同的功能?使用def?

  def main():
d = {} $ b $ ]:
d [x] = lambda:print(x)

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


if __name__ =='__main__':
main()


代码中 lambda 的主体引用名称 x 。与该名称相关联的值在循环的下一次迭代中被改变,所以当lambda被调用并且它解析了它的名字时,它就获得了新的值。为了达到预期的结果,将循环中的 x 的值绑定到 lambda ,然后引用该参数,如下所示:
$ b $ pre $ 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


Possible Duplicate:
Use value of variable in lambda expression

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

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

but the output is 2 2

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

解决方案

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.

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天全站免登陆