“拉姆达"究竟是什么?在 Python 中? [英] What exactly is "lambda" in Python?
问题描述
我想知道python中的lambda
到底是什么?以及在哪里以及为什么使用它.谢谢
I want to know what exactly is lambda
in python? and where and why it is used.
thanks
推荐答案
Lambda 与其说是其他任何东西,不如说是一种概念或编程技术.
Lambda is more of a concept or programming technique then anything else.
基本上它的想法是你得到一个函数(python 中的第一类对象)作为另一个函数的结果而不是对象或原始类型的结果返回.我知道,这很令人困惑.
Basically it's the idea that you get a function (a first-class object in python) returned as a result of another function instead of an object or primitive type. I know, it's confusing.
从 python 文档中查看此示例:
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
f(0)
>>> 42
f(1)
>>> 43
因此 make_incrementor 创建了一个在其结果中使用 n 的函数.您可以拥有一个将参数增加 2 的函数,如下所示:
So make_incrementor creates a function that uses n in it's results. You could have a function that would increment a parameter by 2 like so:
f2 = make_incrementor(2)
f2(3)
>>> 5
在函数式编程和 lisp & 等函数式编程语言中,这是一个非常强大的想法.方案.
This is a very powerful idea in functional programming and functional programming languages like lisp & scheme.
希望这会有所帮助.
这篇关于“拉姆达"究竟是什么?在 Python 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!