lambda 匿名函数

  • 什么是lambda?

lambda 操作符(或 lambda 函数)通常用来创建小巧的,一次性的匿名函数对象。它的基本语法如下:

lambda arguments : expression

lambda 操作符可以有任意数量的参数,但是它只能有一个表达式,且不能包含任何语句,返回一个可以赋值给任何变量的函数对象。

  • lambda 匿名函数示例:
In [73]: add = lambda x, y : x + y

In [74]: add
Out[74]: <function __main__.<lambda>(x, y)> In [75]: print(add(1, 2))
3
  • lambda 匿名函数理解:

在lambda x, y : x + y中,x和y是函数的参数,x+y是表达式,它被执行并返回结果。

lambda x, y : x + y返回的是一个函数对象,它可以被赋值给任何变量。在本例中函数对象被赋值给了 add 变量。如果我们查看 add 的 type,可以看到它是一个 Function。

type(add)

Output: function

绝大多数 lambda 函数作为一个参数传给一个需要函数对象为参数的函数,比如 map,reduce,filter 等函数。

map

  • map的基本语法如下:

    map(function_object, iterable1, iterable2, ...)

    map函数需要一个函数对象和任意数量的 iterables,如 list、dictionary 等。它为序列中的每个元素执行 function_object,并返回由函数对象修改的元素组成的列表。

  • map 示例如下:

In [64]: def add(x):
...: return x+2
...:
...: In [65]: list(map(add, [1,2,3,4]))
Out[65]: [3, 4, 5, 6]

在上面的例子中,map 对 list 中的每个元素1,2,3,4执行 add 函数并返回[3,4,5,6]。接着看看,如何用 map 和 lambda 重写上面的代码:

In [67]: list(map(lambda x: x+2, [1,2,3,4]))
Out[67]: [3, 4, 5, 6]
  • 使用 map 和 lambda 迭代 dictionary:
In [70]: dict_a = [
...: {'name': 'python', 'points': 10},
...: {'name': 'java', 'points': 8}
...: ] In [71]: list(map(lambda x : x['name'], dict_a))
Out[71]: ['python', 'java']

以上代码中,dict_a 中的每个dict作为参数传递给 lambda 函数。 lambda 函数表达式作用于每个 dict 的结果作为输出。

  • map 函数作用于多个 iterables:
In [53]: list_a = [1, 2, 3]

In [54]: list_b = [10, 20, 30]

In [55]: list(map(lambda x, y: x + y, list_a, list_b))
Out[55]: [11, 22, 33]

这里,list_a 和 list_b 的第 i 个元素作为参数传递给 lambda 函数。

在 Python3 中,map 函数返回一个惰性计算(lazily evaluated)的迭代器(Iterator)或 map 对象。就像 zip 函数是惰性计算那样。

我们不能通过 index 访问 map 对象的元素,也不能使用 Len() 得到它的长度。

但我们可以强制转换 map 对象为 list:

In [47]: map_output = map(lambda x: x*2, [1, 2, 3, 4])

In [48]: map_output
Out[48]: <map at 0x1024e4a90> In [49]: list(map_output)
Out[49]: [2, 4, 6, 8]

filter

  • filter 的基本语法如下:

filter(function_object, iterable)

filter 函数需要两个参数,function_object 返回一个布尔值(boolean),对 iterable 的每一个元素调用 function_object,filter 只返回满足 function_object 为 True 的元素。

和 map 函数一样,filter 函数也返回一个 list,但与 map 函数不同的是,filter 函数只能有一个 iterable 作为输入。

  • 过滤出奇数
In [45]: def is_even(x):
...: return x & 1 != 0
...:
...:
...: In [46]: list(filter(is_even, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
Out[46]: [1, 3, 5, 7, 9]
  • 过滤 dicts 的 list:
In [43]: dict_a = [
...: {'name': 'python', 'points': 10},
...: {'name': 'java', 'points': 8}
...: ] In [44]: list(filter(lambda x : x['name'] == 'python', dict_a))
Out[44]: [{'name': 'python', 'points': 10}]

和 map 一样,filter 函数在 Python3 中返回一个惰性计算的 filter 对象或迭代器。我们不能通过 index 访问 filter 对象的元素,也不能使用 Len() 得到它的长度。

In [37]: list_a = [1, 2, 3, 4, 5]

In [38]: filter_obj = filter(lambda x: x % 2 == 0, list_a)

In [39]: even_num = list(filter_obj)

In [40]: even_num
Out[40]: [2, 4]

reduce 函数

  • 什么是 reduce 函数?

reduce 函数会对参数序列中元素进行累积。

reduce 函数语法:

reduce(function, sequence[, initial]) -> value

function 参数是一个有两个参数的函数,reduce 依次从 sequence 中取一个元素,和上一次调用 function 的结果做参数再次调用 function。

第一次调用 function 时,如果提供 initial 参数,会以 sequence 中的第一个元素和 initial 作为参数调用 function,否则会以序列 sequence 中的前两个元素做参数调用 function。

  • reduce 示例:
In [34]: from functools import reduce
...: reduce(lambda x, y: x + y, [2, 3, 4, 5, 6], 1)
...:
Out[34]: 21
In [35]: reduce(lambda x, y: x + y, [2, 3, 4, 5, 6])
Out[35]: 20

注意 function 函数不能为 None。

reversed

  • 什么是 reversed

    reversed()函数是返回序列seq的反向访问的迭代子。参数可以是列表,元组,字符串,不改变原对象。

    reversed()之后,只在第一次遍历时返回值。
  • reversed 示例:
In [1]: a_list = [1, 2,  3, 4, 5]

In [2]: new_list = reversed(a_list)

In [3]: a_list
Out[3]: [1, 2, 3, 4, 5] In [4]: new_list
Out[4]: <list_reverseiterator at 0x10d714f28> In [5]: for i in new_list:
...: print(i)
...:
5
4
3
2
1 In [6]: for i in new_list:
...: print(i)
...: In [7]:

参考资料:

https://www.toutiao.com/a6612880904165523982/?tt_from=weixin&utm_campaign=client_share&wxshare_count=1&timestamp=1539761465&app=news_article&utm_source=weixin&iid=46504004486&utm_medium=toutiao_android&group_id=6612880904165523982

https://blog.csdn.net/sxingming/article/details/51353379

lambda 、 map 、filter 、reduce 及 reversed 常用函数的更多相关文章

  1. python中的内置函数lambda map filter reduce

    p.p1 { margin: 0; font: 12px "Helvetica Neue" } p.p2 { margin: 0; font: 12px "Helveti ...

  2. Python面试题之Python中的lambda map filter reduce zip

    当年龟叔想把上面列出来的这些都干掉.在 “All Things Pythonic: The fate of reduce() in Python 3000”这篇文章中,他给出了自己要移除lambda. ...

  3. lambda,map,filter,reduce

    lambda 编程中提到的 lambda 表达式,通常是在需要一个函数,但是又不想费神去命名一个函数的场合下使用,也就是指匿名函数.返回一个函数对象. func = lambda x,y:x+y fu ...

  4. python 内置函数 map filter reduce lambda

    map(函数名,可遍历迭代的对象) # 列组元素全加 10 # map(需要做什么的函数,遍历迭代对象)函数 map()遍历序列得到一个列表,列表的序号和个数和原来一样 l = [2,3,4,5,6, ...

  5. python常用函数进阶(2)之map,filter,reduce,zip

    Basic Python : Map, Filter, Reduce, Zip 1-Map() 1.1 Syntax # fun : a function applying to the iterab ...

  6. 数组的高阶方法map filter reduce的使用

    数组中常用的高阶方法: foreach    map    filter    reduce    some    every 在这些方法中都是对数组中每一个元素进行遍历操作,只有foreach是没有 ...

  7. 如何在python3.3用 map filter reduce

    在3.3里,如果直接使用map(), filter(), reduce(), 会出现 >>> def f(x): return x % 2 != 0 and x % 3 != 0  ...

  8. Swift map filter reduce 使用指南

    转载:https://useyourloaf.com/blog/swift-guide-to-map-filter-reduce/ Using map, filter or reduce to ope ...

  9. STL之map与pair与unordered_map常用函数详解

    STL之map与pair与unordered_map常用函数详解 一.map的概述 map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称 ...

随机推荐

  1. ubuntu上安装 MySQL 启动/停止 连接MySQL

    1.Ubuntu上安装MySQL服务   1.安装服务端   sudo apt-get install mysql-server    2.安装客户端   sudo apt-get install m ...

  2. HBase实验(CRUD和MR入库)

    目录 前期准备 在HBase shell中实现CRUD操作 1. 启动命令行客户端 2. 创建表 3. 删除.新增列族 4. 删除表teacher 5. 新增数据 6. 查看数据 用Java API实 ...

  3. MaskBlt 拷贝非矩形区域图象

    MaskBlt  该函数使用特定的掩码和光栅操作来对源和目标位图的颜色数据进行组合. 原型: BOOL MaskBlt( HDC  hdcDest, int  nXDest,  int  nYDest ...

  4. docker-compose搭建单机多节点es + kibana

    docker-compose.yml配置如下: version: '2.2' services: elasticsearch: image: docker.elastic.co/elasticsear ...

  5. sqlserver job 执行时间

    select instance_id,jh.run_date,jh.job_id,jh.step_name, case jh.run_status then 'failed' then 'Succee ...

  6. Python next() 函数

    Python next() 函数  Python 内置函数 描述 next() 返回迭代器的下一个项目. 语法 next 语法: next(iterator[, default]) 参数说明: ite ...

  7. ASP.NET 网页动态添加客户端脚本

    在System.Web.UI.Page类中包含了RegisterStarupScript()和RegisterClientScriptBlock()两个方法,使用这两个方法可以实现向Web页面动态添加 ...

  8. QEMU 代码分析:BIOS 的加载过程

    http://www.ibm.com/developerworks/cn/linux/1410_qiaoly_qemubios/ QEMU 中使用 BIOS 简介 BIOS 提供主板或者显卡的固件信息 ...

  9. mybatis框架中的输入映射

    mybatis.xml映射文件中定义了操作数据库的sql,每个sql是一个statement,映射文件是mybatis的核心. 输入类型: 1.传递简单类型 可以参考我之前的对于数据库增删改查的博文. ...

  10. MVC数据注解

    数据注解 using System.ComponentModel.DataAnnotations; KeyAttribute 唯一主键StringLengthAttribute 字符串长度约束MaxL ...