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

问题描述:

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

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,它源自 Lambda微积分和(AFAIK)最初是在 Lisp 中实现的,基本上是匿名的函数-一个没有名称的函数,该函数可在线使用,换句话说,您可以在一个表达式中为lambda函数分配一个标识符,如下所示:

Lambda, which originated from Lambda Calculus and (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:

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

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

This assigns addTwo to 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 return keyword.

上面的代码大致等同于:

The code above is roughly equivalent to:

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

除非您未使用函数定义,否则将为lambda分配一个标识符.

Except you're not using a function definition, you're assigning an identifier to the 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 one time and not numerous times, in which case you would be better off with a function definition.

使用lambda的哈希树示例:

Example of a hash tree using lambdas:

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

在此示例中,我实际上并不想为这两个函数中的任何一个定义名称,因为我只会在哈希中使用它们,因此,我将使用lambda.

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.