当前位置: 首页 > 编程日记 > 正文

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:)

  • Official Docs

    官方文件

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

相关文章:

JAVA-初步认识-第十一章-object类-equals方法覆盖

一. 现在要谈论equals方法另一个方面。如果不写equals方法,直接用来比较也是可以的,貌似equals方法有点多余。 现在不比较对象是否相等,而是比较对象中的特定内容,比如说对象的年龄,之前的写法如下 其实这个方法写完后…

JPPhotoBrowserDemo--微信朋友圈浏览图片

JPPhotoBrowserDemo Browse picture like WeChat. GithubDemo 使用 CocoaPods pod JPPhotoBrowser 在使用的页面中 引用 #import "JPPhotoBrowserManager.h"下载使用 直接将下载文件中的 JPPhotoBrowser 文件夹拖入项目中在使用的页面中 引用 #import "JPPhot…

STM32F103 与 STM32F407引脚兼容问题

突袭网收集的解决方案如下 解决方案1: STM32F103有的功能407都有,并且这些功能的引脚完全兼容,只是程序不同而已。。。而STM32F407有的功能103不一定有,因为407强大些。。。。。。希望对你有用 解决方案2: 不能。407支…

getdate函数_SQL日期函数和GETDATE解释为带有语法示例

getdate函数There are 61 Date Functions defined in MySQL. Don’t worry, we won’t review them all here. This guide will give you an introduction to some of the common ones, and enough exposure for you to comfortably to explore on your own.MySQL中定义了61种日…

JPTagView-多样化的标签View

JPTagView Customized tag pages GitHubDemo 使用 CocoaPods pod JPTagView 在使用的页面中 引用 #import "JPTagView.h"下载使用 直接将下载文件中的 JPTagView 文件夹拖入项目中在使用的页面中 引用 #import "JPTagView.h"使用方法见demo

zsh 每次打开Terminal都需要source bash_profile问题

zsh 每次打开Terminal都需要source bash_profile问题 zsh加载的是 ~/.zshrc文件,而 ‘.zshrc’ 文件中并没有定义任务环境变量。 解决办法,在~/.zshrc文件最后,增加一行: source .bash_profile alias alias gs"git status&q…

解析json实例

解析项目目录中的一个json文件,将之转化为List的一个方法。 package com.miracles.p3.os.util;import com.miracles.p3.os.mode.VideoBean; import org.json.JSONArray; import org.json.JSONObject;import java.util.ArrayList; import java.util.List;/*** Create…

创建bdlink密码是数字_如何创建实际上是安全的密码

创建bdlink密码是数字I am very tired of seeing arbitrary password rules that are different for every web or mobile app. Its almost like these apps arent following a standard and are just making up their own rules that arent based on good security practices.…

通过分离dataSource 让我们的code具有更高的复用性.

转载自汪海的实验室 一 定义dataSource dataSource.h[objc] view plaincopytypedef void (^TableViewCellConfigureBlock)(id cell, id item); interface GroupNotificationDataSource : NSObject<UITableViewDataSource> - (id)initWithItems:(NSArray *)anItems …

复习心得 JAVA异常处理

java中的异常处理机制主要依赖于try&#xff0c;catch&#xff0c;finally&#xff0c;throw&#xff0c;throws五个关键字。其中&#xff0c; try关键字后紧跟一个花括号括起来的代码块&#xff08;花括号不可省略&#xff09;简称为try块。里面放置可能发生异常的代码。 catc…

Linux下Shell重定向

1. 标准输入&#xff0c;标准输出与标准错误输出 Linux下系统打开3个文件&#xff0c;标准输入&#xff0c;标准输出&#xff0c;标准错误输出。 标准输入:从键盘输入数据&#xff0c;即从键盘读入数据。 标准输出:把数据输出到终端上。 标准错误输出:把标准错误输出到终端上。…

sql avg函数使用格式_SQL AVG-SQL平均函数用语法示例解释

sql avg函数使用格式什么是SQL平均(AVG)函数&#xff1f; (What is the SQL Average (AVG) Function?) “Average” is an Aggregate (Group By) Function. It’s used to calculate the average of a numeric column from the set of rows returned by a SQL statement.“平均…

qml学习笔记(二):可视化元素基类Item详解(上半场anchors等等)

原博主博客地址&#xff1a;http://blog.csdn.net/qq21497936本文章博客地址&#xff1a;http://blog.csdn.net/qq21497936/article/details/78516201 qml学习笔记(二)&#xff1a;可视化元素基类Item详解&#xff08;上半场anchors等等&#xff09; 本学章节笔记主要详解Item元…

使用PowerShell登陆多台Windows,测试DCAgent方法

目标&#xff1a; 需要1台PC用域账户远程登陆10台PC&#xff0c;每台登陆后的PC执行发送敏感数据的操作后&#xff0c;再logoff。 在DCAgent服务器上&#xff0c;查看这10个用户每次登陆时&#xff0c;DCAgent是否能获取到登陆信息&#xff08;IP&#xff1a;User&#xff09; …

优雅地分离tableview回调

你是否遇到过这样的需求,在tableview中显示一列数据,点击某一个cell时&#xff0c;在此cell下显示相应的附加信息。如下图&#xff1a;你是不是觉得需求很容易实现&#xff0c;只要使用tableview的insertRowsAtIndexPaths:withRowAnimation:插入一个附加cell就可以了&#xff0…

next.js_Next.js手册

next.jsI wrote this tutorial to help you quickly learn Next.js and get familiar with how it works.我编写本教程是为了帮助您快速学习Next.js并熟悉其工作方式。 Its ideal for you if you have zero to little knowledge of Next.js, you have used React in the past,…

Redux 入门教程(一):基本用法

一年半前&#xff0c;我写了《React 入门实例教程》&#xff0c;介绍了 React 的基本用法。 React 只是 DOM 的一个抽象层&#xff0c;并不是 Web 应用的完整解决方案。有两个方面&#xff0c;它没涉及。代码结构组件之间的通信对于大型的复杂应用来说&#xff0c;这两方面恰恰…

Elasticsearch——Rest API中的常用用法

本篇翻译的是Elasticsearch官方文档中的一些技巧&#xff0c;是使用Elasticsearch必不可少的必备知识&#xff0c;并且适用于所有的Rest Api。 返回数据格式化 当在Rest请求后面添加?pretty时&#xff0c;结果会以Json格式化的方式显示。另外&#xff0c;如果添加?formatyaml…

Python几种主流框架

从GitHub中整理出的15个最受欢迎的Python开源框架。这些框架包括事件I/O&#xff0c;OLAP&#xff0c;Web开发&#xff0c;高性能网络通信&#xff0c;测试&#xff0c;爬虫等。 Django: Python Web应用开发框架Django 应该是最出名的Python框架&#xff0c;GAE甚至Erlang都有框…

Git Fetch vs Pull:Git Fetch和Git Pull命令之间有什么区别?

Git pull and fetch are two commands that are regularly used by Git users. Let’s see the difference between both commands.Git pull和fetch是Git用户经常使用的两个命令。 让我们看看两个命令之间的区别。 For the sake of context, it’s worth remembering that we’…

Redux 入门教程(二):中间件与异步操作

上一篇文章&#xff0c;我介绍了 Redux 的基本做法&#xff1a;用户发出 Action&#xff0c;Reducer 函数算出新的 State&#xff0c;View 重新渲染。但是&#xff0c;一个关键问题没有解决&#xff1a;异步操作怎么办&#xff1f;Action 发出以后&#xff0c;Reducer 立即算出…

day09_读写分离_组件介绍

mysql中间件研究&#xff08;Mysql-prxoy&#xff0c;Atlas&#xff0c;阿米巴&#xff0c;cobar&#xff0c;TDDL&#xff09;mysql-proxyMySQL Proxy就是这么一个中间层代理&#xff0c;简单的说&#xff0c;MySQL Proxy就是一个连接池&#xff0c;负责将前台应用的连接请求转…

Idea其他设置

一、生成javadoc Tools->Gerenate JavaDoc 1. 选择是整个项目还是模块还是单个文件 2. 文档输出路径 3. Locale 选择地区&#xff0c;这个决定了文档的语言&#xff0c;中文就是zh_CN 4. 传入JavaDoc的参数&#xff0c;一般这样写 -encoding UTF-8 -charset UTF-8 -windowti…

freecodecamp_常见技术支持问题– freeCodeCamp常见问题解答

freecodecamp问题&#xff1a;我刚刚登录我的帐户&#xff0c;但看不到过去的任何进展。 (Question: I just signed into my account and I dont see any of my past progress.) Answer: You have created a duplicate account. Sign out of your account and try signing in u…

Redux 入门教程(三):React-Redux 的用法

前两篇教程介绍了 Redux 的基本用法和异步操作&#xff0c;今天是最后一部分&#xff0c;介绍如何在 React 项目中使用 Redux。 为了方便使用&#xff0c;Redux 的作者封装了一个 React 专用的库 React-Redux&#xff0c;本文主要介绍它。 这个库是可以选用的。实际项目中&…

SDN第二次上机作业

1、安装floodlight 2、生成拓扑并连接控制器floodlight&#xff0c;利用控制器floodlight查看图形拓扑 3、利用字符界面下发流表&#xff0c;使得‘h1’和‘h2’ ping 不通 4、利用字符界面下发流表&#xff0c;通过测试‘h1’和‘h3’的联通性&#xff0c;来验证openflow的har…

[KIWI syslog]Install document

安全日志的标准是rfc5425 它介绍SSL-tunnel日志标准和相关要求的标准定义。此外&#xff0c;IANA分配TCP端口6514作为一个标准的端口安全日志。 安装说明&#xff1a; 1.安装日志服务器 官方下载地址&#xff1a;http://www.kiwisyslog.com/products/. 安装步骤&#xff1a; 转…

机器学习数据拆分_解释了关键的机器学习概念-数据集拆分和随机森林

机器学习数据拆分数据集分割 (Dataset Splitting) Splitting up into Training, Cross Validation, and Test sets are common best practices. This allows you to tune various parameters of the algorithm without making judgements that specifically conform to trainin…

Oracle 导表异常处理方案 (解决空表导出出错问题)

Select alter table ||table_name|| allocate extent; from user_tables where num_rows0 or num_rows is null 然后执行查询语句 再导出数据 一个语句搞定&#xff1a; declare stmt varchar2(200); begin for tb in (select table_name from user_tables where seg…

10个你必须知道的ios框架

你好&#xff0c;iOS 开发者们&#xff01;我的名字叫 Pawe?&#xff0c;我是一个独立 iOS 开发者&#xff0c;并且是 Enter Universe 的作者。 接近两年前我发布了iOS开源库&#xff0c;让你的开发坐上火箭吧。这是我在这里最棒的文章了&#xff08;根据 Medium 用户的反馈来…