Python中的Lambda表达式

Lambda表达式 (Lambda Expressions)

Lambda Expressions are ideally used when we need to do something simple and are more interested in getting the job done quickly rather than formally naming the function. Lambda expressions are also known as anonymous functions.

当我们需要做一些简单的事情并且对快速完成工作而不是正式命名函数更感兴趣时,Lambda表达式是理想的选择。 Lambda表达式也称为匿名函数。

Lambda Expressions in Python are a short way to declare small and anonymous functions (it is not necessary to provide a name for lambda functions).

Python中的Lambda表达式是声明小型匿名函数的一种简短方法(不必为lambda函数提供名称)。

Lambda functions behave just like regular functions declared with the def keyword. They come in handy when you want to define a small function in a concise way. They can contain only one expression, so they are not best suited for functions with control-flow statements.

Lambda函数的行为就像使用def关键字声明的常规函数​​一样。 当您想以简洁的方式定义小功能时,它们会派上用场。 它们只能包含一个表达式,因此它们最不适合带有控制流语句的函数。

Lambda函数的语法 (Syntax of a Lambda Function)

lambda arguments: expression

lambda arguments: expression

Lambda functions can have any number of arguments but only one expression.

Lambda函数可以具有任意数量的参数,但只能有一个表达式。

范例程式码 (Example code)

# Lambda function to calculate square of a number
square = lambda x: x ** 2
print(square(3)) # Output: 9

# Traditional function to calculate square of a number
def square1(num):
  return num ** 2
print(square(5)) # Output: 25

In the above lambda example, lambda x: x ** 2 yields an anonymous function object which can be associated with any name. So, we associated the function object with square. So from now on we can call the square object like any traditional function, for example square(10)

在上面的lambda示例中, lambda x: x ** 2产生一个匿名函数对象,该对象可以与任何名称关联。 因此,我们将功能对象与square相关联。 因此,从现在开始,我们可以像任何传统函数一样调用square对象,例如square(10)

Lambda函数的示例 (Examples of lambda functions)

初学者 (Beginner)

lambda_func = lambda x: x**2 # Function that takes an integer and returns its square
lambda_func(3) # Returns 9

中间 (Intermediate)

lambda_func = lambda x: True if x**2 >= 10 else False
lambda_func(3) # Returns False
lambda_func(4) # Returns True

复杂 (Complex)

my_dict = {"A": 1, "B": 2, "C": 3}
sorted(my_dict, key=lambda x: my_dict[x]%3) # Returns ['C', 'A', 'B']

用例 (Use-case)

Let’s say you want to filter out odd numbers from a list. You could use a for loop:

假设您要从list过滤掉奇数。 您可以使用for循环:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered = []

for num in my_list:
     if num % 2 != 0:
         filtered.append(num)

print(filtered)      # Python 2: print filtered
# [1, 3, 5, 7, 9]

Or you could write this as a one liner with list-comprehensions:

或者,您可以将其编写为具有列表理解力的一体式班轮:

filtered = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if x % 2 != 0]

But you might be tempted to use the built-in filter function. Why? The first example is a bit too verbose and the one-liner can be harder to understand. But filter offers the best of both words. What is more, the built-in functions are usually faster.

但是您可能会想使用内置的filter功能。 为什么? 第一个示例过于冗长,难以理解。 但是filter提供了两个词中最好的。 而且,内置功能通常更快。

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

filtered = filter(lambda x: x % 2 != 0, my_list)

list(filtered)
# [1, 3, 5, 7, 9]

NOTE: in Python 3 built in functions return generator objects, so you have to call list. In Python 2, on the other hand, they return a list, tupleor string.

注意:在Python 3中,内置函数返回生成器对象,因此您必须调用list 。 另一方面,在Python 2中,它们返回一个listtuplestring

So what happened? You told filter to take each element in my_list and apply the lambda expressions. The values that return False are filtered out.

所以发生了什么事? 您告诉filter接受my_list每个元素并应用lambda表达式。 返回False的值将被过滤掉。

更多信息: (More Information:)

翻译自: https://www.freecodecamp.org/news/lambda-expressions-in-python/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值