[英]what is the difference for python between lambda and regular function?
I'm curious about the difference between lambda
function and a regular function (defined with def
) - in the python level.我很好奇
lambda
function 和常规 function(用def
定义)之间的区别 - 在 python 级别。 (I know what is the difference for programmers and when to use each one.) (我知道程序员有什么区别以及何时使用它们。)
>>> def a():
return 1
>>> b = lambda: 1
>>> a
<function a at 0x0000000004036F98>
>>> b
<function <lambda> at 0x0000000004031588>
As we can see - python knows that b
is a lambda
function and a
is a regular function. why is that?正如我们所见 - python知道
b
是一个lambda
function 而a
是一个普通的 function。这是为什么呢? what is the difference between them to python ?它们与 python有什么区别?
They are the same type so they are treated the same way:它们是相同的类型,因此它们的处理方式相同:
>>> type(a)
<type 'function'>
>>> type(b)
<type 'function'>
Python also knows that b
was defined as a lambda function and it sets that as function name: Python 也知道
b
被定义为一个 lambda 函数并将其设置为函数名:
>>> a.func_name
'a'
>>> b.func_name
'<lambda>'
In other words, it influences the name that the function will get but as far as Python is concerned, both are functions which means they can be mostly used in the same way.换句话说,它会影响函数将获得的名称,但就 Python 而言,两者都是函数,这意味着它们主要可以以相同的方式使用。 See mgilson's comment below for an important difference between functions and lambda functions regarding pickling.
有关酸洗的函数和 lambda 函数之间的重要区别,请参阅下面的 mgilson 评论。
The only difference is that (a) the body of a lambda can consist of only a single expression, the result of which is returned from the function created and (b) a lambda
expression is an expression which evaluates to a function object, while a def
statement has no value, and creates a function object and binds it to a name.唯一的区别是 (a) lambda 的主体只能由单个表达式组成,其结果从创建的函数返回; (b)
lambda
表达式是一个计算结果为函数对象的表达式,而 a def
语句没有值,并创建一个函数对象并将其绑定到一个名称。
In all other material respects they result in identical objects - the same scope and capture rules apply.在所有其他物质方面,它们导致相同的对象 - 适用相同的范围和捕获规则。 (Immaterial differences are that
lambda
-created functions have a default func_name
of "<lambda>"
. This may affect operation in esoteric cases - eg attempts to pickle functions.). (无关紧要的区别是
lambda
创建的函数的默认func_name
为"<lambda>"
。这可能会影响深奥情况下的操作 - 例如尝试pickle 函数。)。
Both lambda
and def
create the same kind of function – they have the same kind of metadata and capabilities. lambda
和def
创建相同类型的 function——它们具有相同类型的元数据和功能。 Their technical difference is syntactical :它们的技术差异是语法上的:
lambda
is an expression producing a function. lambda
是一个产生 function 的表达式。def
is a statement producing a function. def
是生成 function 的语句。 This is everything that dictates how they can be used .这是决定如何使用它们的一切。 Other apparent differences simply come from the information
lambda
/ def
can capture.其他明显的差异仅来自
lambda
/ def
可以捕获的信息。
>>> def def_func(): pass
>>> lambda_func = lambda: None
>>> type(def_func) == type(lambda_func)
True
A lambda
is more flexible as expressions can be part of more language constructs. lambda
更灵活,因为表达式可以是更多语言结构的一部分。
# v--------------v arguments must be expressions
sort(values, key=lambda x: abs(x))
In contrast, a def
is more powerful as it can consist of more language constructs.相反,
def
更强大,因为它可以包含更多的语言结构。
def encode(num, base):
while num: # statements must be inside statements
num, bit = divmod(num, base)
yield bit
These differences derive directly from one being an expression and the other being a statement.这些差异直接源于一个是表达式,另一个是语句。 Python has no special rules to decide where a
lambda
/ def
may be used. Python 没有特殊规则来决定在哪里可以使用
lambda
/ def
。
<lambda>
s grow<lambda>
生长的地方The primary reason to assume lambda
and def
correspond to different kinds of function is metadata : lambda
is often referred to as an "anonymous function" and miraculously it always produces a function <lambda>
.假设
lambda
和def
对应于不同种类的 function 的主要原因是元数据: lambda
通常被称为“匿名函数”并且奇迹般地它总是产生function <lambda>
。 Other quirks include "lambda functions can't be pickled", and recently typing also does "not work" for lambda
.其他怪癖包括“无法腌制 lambda 函数”,并且最近输入对于
lambda
也“不起作用”。
That is because compared to def
syntax, the lambda
syntax has no way of specifying name, type annotations and similar.这是因为与
def
语法相比, lambda
语法无法指定名称、类型注释等。 As such, Python simply fills in sane defaults for either: the name becomes <lambda>
and annotations are left empty.因此,Python 只是简单地为两者填写合理的默认值:名称变为
<lambda>
并且注释留空。
>>> identity = lambda a: a
>>> identity.__qualname__
'<lambda>'
>>> identity.__annotations__
{}
Since <lambda>
is not a valid identifier, everything using this metadata to find the function – most prominently pickle
– fails.由于
<lambda>
不是有效标识符,因此使用此元数据查找 function(最显着的是pickle
)的所有操作都失败了。
However, that does not make the function an "anonymous function" type.但是,这并不会使 function 成为“匿名函数”类型。 The metadata can be patched up to insert what
def
would provide:可以修补元数据以插入
def
将提供的内容:
>>> identity.__qualname__ = identity.__name__ = 'identity'
>>> identity
<function __main__.identity(a)>
Of course at that one point one can just use def
…当然,在那一点上可以只使用
def
……
lambda
creates an anonymous function. lambda
创建一个匿名函数。 This idea has been taken from functional programming languages.这个想法来自函数式编程语言。 In this way you can create and pass the function to other functions like
map
and filter
.通过这种方式,您可以创建函数并将其传递给其他函数,例如
map
和filter
。 (look here ) (看这里)
You can pass normal functions to these functions too, but since mostly they are simple and they are not used anywhere else, it's inconvenient to go through the whole process of definfing a new function.您也可以将普通函数传递给这些函数,但由于它们大多很简单并且不会在其他任何地方使用,因此不方便完成定义新函数的整个过程。
As an example take a look at this:作为一个例子,看看这个:
>>> a = [1, 2, 3, 4]
>>> print map( lambda x : x*2 + 1, a )
[3, 5, 7, 9, 11]
Lambda is an inline function where we can do any functionality without a function name. Lambda 是一个内联函数,我们可以在没有函数名称的情况下执行任何功能。 It is helpful when we use it as an argument to a higher-order function.
当我们将其用作高阶函数的参数时,这很有帮助。 Eg: A function that takes in other functions as arguments.
例如:一个接受其他函数作为参数的函数。
Example of Function definition:函数定义示例:
>>> def func(a, b):
return a * b
>>> func(2,3)
6
>>> type(func)
<class 'function'>
>>> func
<function func at 0x034B6E88>
Example of Lambda expression: Lambda 表达式示例:
>>> multiply = lambda a, b: a * b
>>> multiply(2, 3)
6
>>> type(multiply)
<class 'function'>
>>> multiply
<function <lambda> at 0x034B6ED0>
Both returns same output value.两者都返回相同的输出值。 Only object returned are different.
只有返回的对象不同。 "func" name for Function and for Lambda.
函数和 Lambda 的“func”名称。
First consider the diff b/w the two.首先考虑两者的差异黑白。
Lambda functions: are operator can have any number of arguments, but it can have only one expression. Lambda 函数: are 运算符可以有任意数量的参数,但只能有一个表达式。 It cannot contain any statements and it returns a function object which can be assigned to any variable.
它不能包含任何语句,它返回一个可以分配给任何变量的函数对象。 They can be used in the block they were created.
它们可以在它们创建的块中使用。
def functions: Functions help break our program into smaller and modular chunks. def 函数:函数有助于将我们的程序分解成更小的模块化块。 As our program grows larger and larger, functions make it more organised and manageable.
随着我们的程序变得越来越大,函数使它更有条理和易于管理。 They can be called and used anywhere we want.
它们可以在我们想要的任何地方调用和使用。
Here you can get more clear difference by following example.在这里,您可以通过以下示例获得更明显的区别。
def add(a,b):
return a+b
print(add(4,5))
add = lambda x, y : x + y
print(add(4,5))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.