“拉姆达"是什么意思?在 Python 中意味着什么,最简单的使用方法是什么? [英] What does "lambda" mean in Python, and what's the simplest way to use it?
问题描述
您能否举出一个示例和其他示例来说明何时以及何时不使用 Lambda?我的书给了我一些例子,但它们令人困惑.
Lambda,源于Lambda Calculus 和 (AFAIK) 首先在 Lisp 中实现,基本上是匿名的函数 - 一个没有名称的函数,并在行内使用,换句话说,您可以在单个表达式中为 lambda 函数分配一个标识符,如下所示:
<预><代码>>>>addTwo = lambda x: x+2>>>添加两个(2)4这将 addTwo
分配给匿名函数,它接受 1 个参数 x,在函数体中它将 2 添加到 x,它返回函数体中最后一个表达式的最后一个值,所以有没有 return
关键字.
上面的代码大致相当于:
<预><代码>>>>def addTwo(x):...返回 x+2...>>>添加两个(2)4除非您没有使用函数定义,否则您正在为 lambda 分配一个标识符.
使用它们的最佳位置是当您真的不想定义带有名称的函数时,可能是因为该函数只会使用一次而不是多次,在这种情况下最好使用函数定义.
使用 lambda 的哈希树示例:
<预><代码>>>>地图树 = {...数字":lambda x:x**x,... '字符串': lambda x: x[1:]... }>>>otype = '数字'>>>mapTree[otype](2)4>>>otype = '字符串'>>>mapTree[otype]('foo')'哦'在这个例子中,我真的不想为这两个函数中的任何一个定义名称,因为我只会在散列中使用它们,因此我将使用 lambdas.
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, 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
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
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.
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'
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.
这篇关于“拉姆达"是什么意思?在 Python 中意味着什么,最简单的使用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!