“lambda”在 Python 中是什么意思,最简单的使用方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1583617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:37:46  来源:igfitidea点击:

What does "lambda" mean in Python, and what's the simplest way to use it?

pythonlambda

提问by TIMEX

Can you give an example and other examples that show when and when not to use Lambda? My book gives me examples, but they're confusing.

您能否举出一个示例和其他示例来说明何时以及何时不使用 Lambda?我的书给了我一些例子,但它们令人困惑。

回答by meder omuraliev

Lambda, which originated from Lambda Calculusand (AFAIK) was first implemented in Lisp, is basically an anonymous function - a function which doesn't have a name, and is used in-line, in other words you can assign an identifier to a lambda function in a single expression as such:

Lambda 起源于Lambda Calculus并且(AFAIK)首先在Lisp 中实现,它基本上是一个匿名函数 - 一个没有名称的函数,并且是内嵌使用的,换句话说,您可以将标识符分配给单个表达式中的 lambda 函数如下:

>>> addTwo = lambda x: x+2
>>> addTwo(2)
4

This assigns addTwoto the anonymous function, which accepts 1 argument x, and in the function body it adds 2 to x, it returns the last value of the last expression in the function body so there's no returnkeyword.

这分配addTwo给匿名函数,它接受 1 个参数 x,在函数体中,它将 2 添加到 x,它返回函数体中最后一个表达式的最后一个值,因此没有return关键字。

The code above is roughly equivalent to:

上面的代码大致相当于:

>>> def addTwo(x):
...     return x+2
... 
>>> addTwo(2)
4

Except you're not using a function definition, you're assigning an identifier to the lambda.

除非您没有使用函数定义,否则您正在为 lambda 分配一个标识符。

The best place to use them is when you don't really want to define a function with a name, possibly because that function will only be used onetime and not numerous times, in which case you would be better off with a function definition.

使用它们的最好的地方是,当你真的不希望定义一个函数的名称,可能是因为该功能将只使用一个时间,而不是无数次,在这种情况下,你会过得更好用的函数定义。

Example of a hash tree using lambdas:

使用 lambda 的哈希树示例:

>>> mapTree = {
...     'number': lambda x: x**x,
...     'string': lambda x: x[1:]
... }
>>> otype = 'number'
>>> mapTree[otype](2)
4
>>> otype = 'string'
>>> mapTree[otype]('foo')
'oo'

In this example I don't really want to define a name to either of those functions because I'll only use them within the hash, therefore I'll use lambdas.

在这个例子中,我真的不想为这两个函数中的任何一个定义名称,因为我只会在散列中使用它们,因此我将使用 lambdas。

回答by Sinan ünür

I do not know which book you are using, but Dive into Pythonhas a sectionwhich I think is informative.

我不知道您在使用哪本书,但是Dive into Python有一个我认为内容丰富的部分。

回答by steveha

Use of lambda is sort of a style thing. When you can get away with a very simple function, and usually where you are just storing it somewhere (in a list of functions perhaps, or in a GUI toolkit data structure, etc.) people feel lambda reduces clutter in their code.

使用 lambda 是一种风格。当您可以摆脱一个非常简单的函数,并且通常只是将它存储在某个地方(可能是在函数列表中,或者在 GUI 工具包数据结构中,等等)时,人们会觉得 lambda 减少了他们代码中的混乱。

In Python it is only possible to make a lambda that returns a single expression, and the lambda cannot span multiple lines (unless you join the multiple lines by using the backslash-at-the-end-of-a-line trick). People have requested that Python add improvements for lambda, but it hasn't happened. As I understand it, the changes to make lambda able to write any function would significantly complicate the parsing code in Python. And, since we already have defto define a function, the gain is not considered worth the complication. So there are some cases where you might wish to use lambda where it is not possible. In that case, you can just use a def:

在 Python 中,只能创建一个返回单个表达式的 lambda,并且 lambda 不能跨越多行(除非您使用反斜杠在行尾的技巧来连接多行)。人们要求 Python 为 lambda 添加改进,但它没有发生。据我了解,使 lambda 能够编写任何函数的更改将使 Python 中的解析代码显着复杂化。而且,由于我们已经必须def定义一个函数,因此认为增益不值得复杂化。因此,在某些情况下,您可能希望在不可能的情况下使用 lambda。在这种情况下,您可以只使用一个def

object1.register_callback_function(lambda x: x.foo() > 3)

def fn(x):
    if x.foo() > 3:
        x.recalibrate()
        return x.value() > 9
    elif x.bar() > 3:
        x.do_something_else()
        return x.other_value < 0
    else:
        x.whatever()
        return True

object2.register_callback_function(fn)
del(fn)

The first callback function was simple and a lambda sufficed. For the second one, it is simply not possible to use a lambda. We achieve the same effect by using defand making a function object that is bound to the name fn, and then passing fnto register_callback_function(). Then, just to show we can, we call del()on the name fnto unbind it. Now the name fnno longer is bound with any object, but register_callback_function()still has a reference to the function object so the function object lives on.

第一个回调函数很简单,一个 lambda 就足够了。对于第二个,根本不可能使用 lambda。我们通过使用def和制作一个绑定到 name 的函数对象,fn然后传递fn到 来实现相同的效果register_callback_function()。然后,为了表明我们可以,我们调用del()名称fn来解除绑定。现在该名称fn不再与任何对象绑定,但register_callback_function()仍然具有对函数对象的引用,因此函数对象仍然存在。