Lambda表达式是求值为函数的表达式,需要指明两部分:参数和返回表达式,其格式为
lambda <parameters>: <return expression>
While both lambda
expressions and def
statements create function objects, there are some notable differences. lambda
expressions work like other expressions; much like a mathematical expression just evaluates to a number and does not alter the current environment, a lambda
expression evaluates to a function without changing the current environment. Let's take a closer look.
Lambda表达式和def语句都创建了函数对象,它们有一些显著的不同。Lambda表达式更像一个数学表达式,仅求值一个数字结果,不改变当前环境(定义了一个不在当前环境中与某个name绑定的函数)。
lambda | def | |
---|---|---|
Type | Expression that evaluates to a value | Statement that alters the environment |
Result of execution | Creates an anonymous lambda function with no intrinsic name. | Creates a function with an intrinsic name and binds it to that name in the current environment. |
Effect on the environment | Evaluating a lambda expression does not create or modify any variables. | Executing a def statement both creates a new function object and binds it to a name in the current environment. |
Usage | A lambda expression can be used anywhere that expects an expression, such as in an assignment statement or as the operator or operand to a call expression. | After executing a def statement, the created function is bound to a name. You should use this name to refer to the function anywhere that expects an expression. |
Example |
# A lambda expression by itself does not alter
# the environment
lambda x: x * x
# We can assign lambda functions to a name
# with an assignment statement
square = lambda x: x * x
square(3)
# Lambda expressions can be used as an operator
# or operand
negate = lambda f, x: -f(x)
negate(lambda x: x * x, 3)
def square(x):
return x * x
# A function created by a def statement
# can be referred to by its intrinsic name
square(3