Lambda Expression

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绑定的函数)。

lambdadef
TypeExpression that evaluates to a valueStatement that alters the environment
Result of executionCreates 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 environmentEvaluating 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.
Usagelambda 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
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值