接受函数作为参数,或者把函数作为结果返回的函数是高阶函数,官方叫做 Higher-order functions。

map()和filter()是内置函数。在python3中,reduce()已不再是内置函数,被放到了functools模块里面,这个函数最常用于求和。

另外,列表推导式和生成器表达式具有map()和filter()两个函数的功能,而且更易于阅读。


map()

在python3中,map()函数返回的是一个可迭代的map对象,可用list()函数转换为列表。

map()函数将参数序列中的元素传递给参数函数,然后将生成的结果返回组成新的可迭代对象。

map()函数可传递多个参数序列,运行方式与zip()函数类似,这里不再细说。

>>> help(map)
Help on class map in module builtins: class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.
Return an iterator that applies function to every item of iterable, yielding the results.
If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted.
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])
<map object at 0x0000000002E86208>
>>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))
[1, 4, 9, 16, 25] >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
<map object at 0x0000000002E86208>
>>> list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
[3, 7, 11, 15, 19]

filter()

在python3中,filter()函数返回的是一个可迭代的filter对象,同样可用list()函数转换为列表。

filter()函数用来过滤序列,参数函数为判断函数,参数序列中判断为真的元素返回组成新的可迭代对象。

>>> help(filter)
Help on class filter in module builtins: class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.
Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.
>>> filter(lambda x: x % 3, range(20))
<filter object at 0x0000000002B7DBE0>
>>> list(filter(lambda x: x % 3, range(20)))
[1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19]

reduce()

reduce()函数会对参数序列中的元素从左到右进行累积,最终reduce为单个value。

reduce()函数直接返回value,而不是迭代器。

>>> from functools import reduce

>>> help(reduce)
Help on built-in function reduce in module _functools: reduce(...)
reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).
If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
>>> reduce(lambda x,y: x+y, [1,2,3,4,5])
15

reduce()函数的参数函数必须跟两个参数,完成从左到右累积。如果不是两个参数,会报 TypeError 异常。

>>> reduce(lambda x: x + 1, [1,2,3,4,5])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes 1 positional argument but 2 were given

参考:

https://docs.python.org/3/library/functools.html

https://docs.python.org/3/library/functions.html#map

https://docs.python.org/3/library/functions.html#filter

https://docs.python.org/3/library/functools.html#functools.reduce

高阶函数map(),filter(),reduce()的更多相关文章

  1. 高阶函数-map/filter/reduce

    什么样的函数叫高阶函数: 条件:1.函数接受函数作为参数 2.函数的返回值中包含函数 高阶函数之----map函数 map(func, *iterables) --> map objectnum ...

  2. 高阶函数map,filter,reduce的用法

    1.filter filter函数的主要用途是对数组元素进行过滤,并返回一个符合条件的元素的数组 let nums = [10,20,30,111,222,333] 选出nums中小于100的数: l ...

  3. Python高阶函数map、reduce、filter、sorted的应用

    #-*- coding:utf-8 -*- from selenium import webdriver from selenium.webdriver.support.wait import Web ...

  4. python的高阶函数(map,filter,sorted,reduce)

    高阶函数 关注公众号"轻松学编程"了解更多. 1.MapReduce MapReduce主要应用于分布式中. 大数据实际上是在15年下半年开始火起来的. 分布式思想:将一个连续的字 ...

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

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

  6. js高阶函数map和reduce

    map 举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个数组[1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map实现如下: 由于map()方法定义在JavaScr ...

  7. python之高阶函数--map()和reduce()

    以下为学习笔记:来自廖雪峰的官方网站 1.高阶函数:简单来说是一个函数里面嵌入另一个函数 2.python内建的了map()和reduce()函数 map()函数接收两参数,一个是函数,一个是Iter ...

  8. python学习笔记1 -- 函数式编程之高阶函数 map 和reduce

    我用我自己,就是高阶函数,直接表现就是函数可以作为另一个函数的参数,也可以作为返回值 首先一个知识点是 函数的表现形式,印象中的是def  fw(参数)这种方式定义一个函数 python有很多的内置函 ...

  9. JS高阶函数--------map、reduce、filter

    一.filter filter用于对数组进行过滤.它创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素. 注意: filter() 不会对空数组进行检测. 注意: filter() ...

随机推荐

  1. storm报错:Exception in thread "main" java.lang.RuntimeException: InvalidTopologyException(msg:Component: [mybolt] subscribes from non-existent stream: [default] of component [kafka_spout])

    问题描述: storm版本:1.2.2,kafka版本:2.11.   在使用storm去消费kafka中的数据时,发生了如下错误. [root@node01 jars]# /opt/storm-1. ...

  2. springboot redis 监听过期key值事件

    redis 中的key值过期后,触发通知事件 1.创建springboot工程,创建监听类 maven配置 <dependencies> <dependency> <gr ...

  3. [Zlib]_[初级]_[使用zlib库压缩和解压STL string]

    场景 1.一般在使用文本json传输数据, 数据量特别大时,传输的过程就特别耗时, 因为带宽或者socket的缓存是有限制的, 数据量越大, 传输时间就越长. 网站一般使用gzip来压缩成二进制. 说 ...

  4. stl源码剖析 详细学习笔记 算法(4)

    //---------------------------15/03/31---------------------------- //lower_bound(要求有序) template<cl ...

  5. ecCodes 学习 利用ecCodes fortran90 api对GRIB文件进行读写

    参考 https://www.ecmwf.int/assets/elearning/eccodes/eccodes2/story_html5.htmlhttps://confluence.ecmwf. ...

  6. 博客目录 Blog directory

    Linux 学习笔记 Linux/Mac 挂载远程服务器目录到本地 --Mount remote server directory to local PC 远程连接服务器端Jupyter Notebo ...

  7. kettle开源项目部署文档

    kettle开源项目部署文档 1.kettle简介 kettle是一款国外开源的ETL(Extract Transform Load)工具,纯java编写,可以在Windows.Linux.Unix上 ...

  8. lambda表达式,map函数

    lambda只是一个表达式,不需要定义函数,故也是匿名函数,用法为:lambda 参数:表达式. x=5 list1=[2,3,4] list2=[10,20,30] s=lambda x:x**3 ...

  9. PAT甲题题解-1030. Travel Plan (30)-最短路+输出路径

    模板题最短路+输出路径如果最短路不唯一,输出cost最小的 #include <iostream> #include <cstdio> #include <algorit ...

  10. 1092. To Buy or Not to Buy (20)-map

    给出两个字符串,判断第二个字符串中的字符是否都出现在第一个中. 是,则输出Yes,以及多余的字符的个数. 否,则输出No,以及缺失的个数. #include <iostream> #inc ...