python中的lambda表达式

介绍 (Introduction)

Imagine we are coding and need to write a simple function. However, we are only going to be using this function once and thus it seems unnecessary to create an entire function with the def keyword for that one task. Well, that’s where lambda expressions come in.

假设我们正在编码,需要编写一个简单的函数。 但是,我们只使用一次此函数,因此似乎没有必要为该任务使用def关键字创建整个函数。 好吧,这就是lambda表达式出现的地方。

什么是lambda表达式? (What are lambda expressions?)

Lambda expressions are used to create anonymous functions, or functions without a name. They are useful when we need to create a function that will only need to be used once (a throw-away function) and can be written in one line. Lambda functions can have any number of parameters but can only have one expression. They generally have this format which yields a function object:

Lambda表达式用于创建匿名函数或没有名称的函数。 当我们需要创建一个只需要使用一次(一次性函数)并且可以一行编写的函数时,它们就很有用。 Lambda函数可以具有任意数量的参数,但只能具有一个表达式。 它们通常具有产生函数对象的这种格式:

lambda parameters: expression

lambda参数:表达式

使用def关键字创建函数 (Creating a Function with def Keyword)

Let’s say we want to write a function that takes in a number as an input and returns that number squared. We can do so by using the def keyword:

假设我们要编写一个函数,该函数接受一个数字作为输入并返回该数字的平方。 我们可以使用def关键字来做到这一点:

def square(num):
   return num**2

We used the def keyword to define this function. We named this function square. This function has one parameter, num, and it returns that number squared using the ** operator.

我们使用def关键字定义此功能。 我们将此函数命名为square 。 此函数有一个参数num ,并使用**运算符返回该数字的平方。

具有一个参数的Lambda表达式 (Lambda Expression with One Parameter)

Let’s now write this function as a lambda expression:

现在让我们将此函数编写为lambda表达式:

lambda num: num**2

And that’s it! We first start with the lambda keyword, then the parameter num, a colon, and what you want that function to return, which is num**2.

就是这样! 我们首先从lambda关键字开始,然后是参数num ,冒号和要返回的函数num ** 2。

Note that this function is anonymous, or does not have a name. So we cannot invoke the function at a later point. In addition, we did not write return. Everything after the colon is part of the expression that will be returned.

请注意,此函数是匿名的,或者没有名称。 因此,我们不能在以后调用该函数。 另外,没写退货。 冒号之后的所有内容都是将要返回的表达式的一部分。

If we want to assign a lambda function to a variable so that it can be invoked later, we can do so by using an assignment operator:

如果我们想为一个变量分配一个lambda函数,以便以后可以调用它,可以使用赋值运算符来实现:

square = lambda num: num**2

We can then invoke or call this function the same way we would with a function that was defined with the def keyword. For example:

然后,我们可以像使用def关键字定义的函数一样调用或调用此函数。 例如:

square(3) # will return 9 as the output

具有多个参数的Lambda表达式 (Lambda Expression with Multiple Parameters)

Let’s make a lambda function that has two parameters instead of just one. First, we will use the def keyword to create a function that returns the sum of two numbers, and then we will write it as a lambda expression:

让我们创建一个具有两个参数而不只是一个参数的lambda函数。 首先,我们将使用def关键字创建一个返回两个数字之和的函数,然后将其编写为lambda表达式:

# using def keyword that returns the sum of num1 and num2
def sum(num1, num2):
  return num1 + num2


# using lambda keyword that returns the sum of num1 and num2
lambda num1, num2: num1 + num2


# can assign the lambda function to a variable
sum = lambda num1, num2: num1 + num2

As we can see, if we want our function to have multiple parameters in a lambda expression, we would just separate those parameters by a comma.

如我们所见,如果我们希望函数在lambda表达式中具有多个参数,则只需将这些参数用逗号分隔即可。

Just like with expressions created using the def keyword, a lambda expression does not need to have any parameters. For example, if we want a lambda expression that takes in no arguments and always returns True, we can write it as follows:

就像使用def关键字创建的表达式一样,lambda表达式不需要任何参数。 例如,如果我们想要一个不带任何参数且始终返回True的lambda表达式,则可以如下编写:

lambda: True

Lambda表达式中的条件语句 (Conditional Statements in Lambda Expressions)

We can also include if else statements in lambda expressions. We would just need to make sure that it is all on one line. For example, let’s create a function that takes in two numbers and returns the greater of those numbers:

我们还可以在lambda表达式中包含if else语句。 我们只需要确保所有内容都在同一行即可。 例如,让我们创建一个接受两个数字并返回这些数字中较大的一个的函数:

# function that takes in num1 and num2 and returns the larger number


# def keyword
def larger_num(num1, num2):
  if num1 > num2:
    return num1
  else: 
    return num2


# using lambda expressions
larger_num = lambda num1, num2: num1 if num1 > num2 else num2

Our lambda expression takes in two numbers, num1 and num2, and returns num1 if num1 is greater than num2, else, it returns num2. Obviously this function doesn’t take into account if the numbers are equal, as it will just return num2 in that case, however, we are just illustrating how we can use conditional statements within a lambda expression.

我们的lambda表达式接受两个数字num1num2 ,如果num1大于num2则返回num1 ,否则返回num2 。 显然,如果数字相等,则不会考虑此函数,因为在这种情况下它将仅返回num2 ,但是,我们仅说明如何在lambda表达式中使用条件语句。

那如果呢? (What About else if?)

Technically we cannot use an elif statement in a lambda expression. However, we can nest if else statements within an else statement to achieve the same result as an elif statement. For example, if we also want to check if num1 is greater than num2, if num2 is greater than num1, or else (meaning if they are equal), we can use the following lambda expression:

从技术上讲,我们不能在lambda表达式中使用elif语句。 但是,我们可以将else语句嵌套在else语句中,以获得与elif语句相同的结果。 例如,如果我们还想检查num1是否大于num2 ,如果num2大于num1 ,否则(意味着它们相等),我们可以使用以下lambda表达式:

larger_num = lambda num1, num2: num1 if num1 > num2 else (num2 if num1 < num2 else 'They are equal')

So if our lambda expression finds that num1 > num2, it will return num1. If this condition is false, it’ll move on to the else statement. Within this else statement (within the parenthesis), it’ll first check if num1 < num2 is true. If that condition is true, it will return num2. If that condition is false, it will return whatever is after the else statement which in this case is the string ‘They are equal’.

因此,如果我们的lambda表达式找到num1 > num2 ,它将返回num1 。 如果此条件为假,它将继续进行else语句。 在else语句中(在括号内),它将首先检查num1 < num2是否为true。 如果该条件为true,则将返回num2 。 如果该条件为假,它将返回else语句之后的任何内容,在本例中为字符串“它们相等”。

最后说明 (Final Note)

Lambda expressions are extremely useful to use in functions that take in another function as an argument. For example, in the map, filter, and reduce functions, we can pass in a lambda expression as the function.

Lambda表达式在将另一个函数作为参数的函数中使用非常有用。 例如,在map,filter和reduce函数中,我们可以传入lambda表达式作为函数。

Detailed overview of the map, filter, and reduce functions:

映射,过滤和归约功能的详细概述:

结论 (Conclusion)

In this tutorial, we learned what lambda expressions are, how to write them with zero parameters, one parameter, and multiple parameters. We also learned how to use if else statements within a lambda expression.

在本教程中,我们学习了什么是lambda表达式,如何使用零参数,一个参数和多个参数编写它们。 我们还学习了如何在lambda表达式中使用if else语句。

翻译自: https://towardsdatascience.com/lambda-expressions-in-python-9ad476c75438

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值