博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python中的Lambda表达式
阅读量:2529 次
发布时间:2019-05-11

本文共 3554 字,大约阅读时间需要 11 分钟。

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 numbersquare = lambda x: x ** 2print(square(3)) # Output: 9# Traditional function to calculate square of a numberdef square1(num):  return num ** 2print(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 squarelambda_func(3) # Returns 9

中间 (Intermediate)

lambda_func = lambda x: True if x**2 >= 10 else Falselambda_func(3) # Returns Falselambda_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:)

翻译自:

转载地址:http://qduzd.baihongyu.com/

你可能感兴趣的文章
SqlServer动态变换库名
查看>>
抓虫记之五:Webservice总是调用不了
查看>>
JS获取父框架的内容:获取子框架的内容:js框架应用
查看>>
关于手码编写autolayout约束
查看>>
Java参考资料
查看>>
goto语句
查看>>
简单的车票管理系统
查看>>
2016年10月25 草堂随笔1 ModelState.IsValid
查看>>
Jenkins Pipelines Summary
查看>>
倾斜摄影 实景三维建模软件photoscan教程
查看>>
Actiion Func ;Donet framework 中已经定义好的委托
查看>>
Python 模块之 xlrd (Excel文件读写)
查看>>
再探@font-face及webIcon制作
查看>>
BZOJ.4212.神牛的养成计划(Trie 可持久化Trie)
查看>>
【unityd--初始学习四--3d世界中的物体移动及角度变换】
查看>>
电脑cmos是什么?和bois的区别?
查看>>
REST WCF 使用Stream进行Server与Client交互
查看>>
Python数据分析之Matplotlib绘制柱状图
查看>>
Django组件之contenttype
查看>>
刘江的博客
查看>>