理解python中的lambda并使用它来传递多个参数 [英] Understanding lambda in python and using it to pass multiple arguments

查看:53
本文介绍了理解python中的lambda并使用它来传递多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了我能在 lambda 上找到的所有内容后,我仍然不明白如何让它做我想做的事.

After reading everything I can find on lambda, I still don't understand how to make it do what I want.

大家举个例子:

lambda x, y : x + y

为什么你需要在 : 之前声明 xy ?还有你如何让它返回多个参数?

Why do you need to state both x and y before the :? Also how do you make it return multiple arguments?

例如:

self.buttonAdd_1 = Button(self, text='+', command=lambda : self.calculate(self.buttonOut_1.grid_info(), 1))

这很好用.但是下面的代码没有:

This works just fine. But the following code does not:

self.entry_1.bind("<Return>", lambda : self.calculate(self.buttonOut_1.grid_info(), 1))

它产生了错误:

TypeError: () 不接受任何参数(给定 1 个)

TypeError: () takes no arguments (1 given)

推荐答案

为什么需要在 ':' 之前同时声明 'x' 和 'y'?

Why do you need to state both 'x' and 'y' before the ':'?

因为 lambda(概念上)与函数相同,只是内联编写的.你的例子相当于

Because a lambda is (conceptually) the same as a function, just written inline. Your example is equivalent to

def f(x, y) : return x + y

只是没有将它绑定到像 f 这样的名称.

just without binding it to a name like f.

还有你如何让它返回多个参数?

Also how do you make it return multiple arguments?

和函数一样.最好返回一个元组:

The same way like with a function. Preferably, you return a tuple:

lambda x, y: (x+y, x-y)

或者一个列表,一个类,或者其他什么.

Or a list, or a class, or whatever.

self.entry_1.bind 的事情应该由 Demosthenex 回答.

The thing with self.entry_1.bind should be answered by Demosthenex.

这篇关于理解python中的lambda并使用它来传递多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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