Python中map()reduce()filter()三个函数均是应用于序列的内置函数,分别对序列进行遍历、递归计算以及过滤操作。这三个内置函数在实际使用过程中常常和“行内函数”lambda函数联合使用,我们首先介绍下lambda函数。

1、lambda函数

lambda函数的Python3.x API文档

lambda
An anonymous inline function consisting of a single expression which is evaluated when the function is called. The syntax to create a lambda function is lambda [arguments]: expression

由文档可知,lambda函数是匿名行内函数,其语法为lambda [arguments]: expression,比如:

f = lambda x, y : x * y #定义了函数f(x, y) = x * y

其非匿名函数表达如下:

def f(x, y):
return x * y

2、map()函数

map()函数的Python3.x API文档

map(function, iterable, ...)
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. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().

map()函数的输入是一个函数function以及一个或多个可迭代的集合iterable,在Python 2.x中map()函数的输出是一个集合,Python 3.x中输出的是一个迭代器。map()函数主要功能为对iterable中的每个元素都进行function函数操作,并将所有的返回结果放到集合或迭代器中。function如果是None,则其作用等同于zip()。

例如:

>>> a = map(lambda x, y : x * y, range(3), range(3))
>>> b = list(a)
>>> print(b)
[0, 1, 4]

在Python 2.x中则不需要 b = list(a),因为在Python 2.x中map()函数的输出直接就是一个集合。

map()函数的具体执行过程图如图1所示。

图 1 map()函数的具体执行过程图

由图1可看出,使用map函数时,两个可迭代的集合中的元素可以并行进行计算。

对于两个可迭代的集合的元素个数不一致的情况,map()函数会自动截断更长的那个集合,并只计算两个集合对应的元素,比如:

>>> a = map(lambda x, y : x * y, range(3), range(2))
>>> b = list(a)
>>> print(b)
[0, 1]

3、reduce()函数

reduce()函数的Python3.x API文档

functools.reduce(function, iterable[, initializer])
Apply function of two arguments cumulatively to the items of 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). The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.

reduce()函数的输入是一个函数function、一个可迭代的集合iterable以及一个可选的初始项initializer,输出为一个值。不同于map()函数对序列中的元素进行逐一遍历,reduce()函数对序列中的元素进行递归计算。比如:

>>> from functools import reduce
>>> a = reduce(lambda x, y : x * y, [1, 2, 3])
>>> print(a)
6

在 Python3 中,reduce() 函数已经被从全局名字空间里移除了,它现在被放置在 functools模块里,如果想要使用它,则需要通过引入 functools 模块来调用 reduce() 函数。

reduce() 函数的具体执行过程图如图2所示。

图2 reduce() 函数的具体执行过程图

由图2可以看出,reduce()函数先将可迭代集合中的前两个元素进行function操作运算,然后将运算结果与第三个元素再进行function操作运算,以此类推,直到迭代完集合中所有的元素,最终返回递归结果。

4、filter()函数

filter()函数的Python3.x API文档

filter(function, iterable)
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 Noneand (item for item in iterable if item) if function is None.
See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.

filter()函数的输入为一个函数function和一个可迭代的集合iterable,在Python 2.x中filter()函数的输出是一个集合,Python 3.x中输出的是一个filter类。顾名思义,filter()函数主要是对指定可迭代集合进行过滤,筛选出集合中符合条件的元素。比如:

>>> a = filter(lambda x: x > 3 and x < 6, range(7))
>>> print(a)
<filter object at 0x108bf2390>
>>> b = list(a)
>>> print(b)
[4, 5]

5、map()、reduce()和filter()与for

在Python的函数式编程中的map()reduce()filter()函数,均可用for循环来实现,那么为什么还需要map()、reduce()和filter()函数呢?

主要是因为Python的for命令效率不高且复杂,而map()reduce()filter()更为高效和简洁,map()reduce()filter()的循环速度比Python内置的for或while循环要快得多,其执行速度相当于C语言。

def demo_for():
x = [x for x in range(100000)]
y = [y for y in range(100000)]
result = []
for i in range(100000):
result.append(x[i] + y[i])
return result def demo_map():
a = map(lambda x, y: x + y, range(100000), range(100000))
return list(a)

在以上的十万个元素的对比计算中,demo_map的执行效率比demo_for的高2倍之多。厦门叉车修理公司

Python函数式编程中map()、reduce()和filter()函数的用法的更多相关文章

  1. Python函数式编程,map/reduce,filter和sorted

    什么是函数式编程? 与面向对象编程(Object-oriented programming)和过程式编程(Procedural programming)并列的编程范式. 最主要的特征是,函数是第一等公 ...

  2. Python学习札记(二十一) 函数式编程2 map/reduce

    参考:map/reduce Note 1.map():map()函数接收两个参数,一个是函数,一个是Iterable.map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回. ...

  3. Python“函数式编程”中常用的函数

    1.map(func,seq[,seq,...]) 对序列中的每个元素应用函数,python2中map()返回的是列表,python3中返回的是迭代器,可以用list()转换成列表.以下例子为pyth ...

  4. 转自:Python函数式编程指南(二):函数

    2. 从函数开始 2.1. 定义一个函数 如下定义了一个求和函数: 1 2 def add(x, y):     return x + y 关于参数和返回值的语法细节可以参考其他文档,这里就略过了. ...

  5. map,reduce和filter函数

    numArray = [1, 2, 3, 4, 5] def ercifang(x): return x ** 2 def map_test(func, numArray): li = [] for ...

  6. Python函数式编程(一):高级函数

    首先有一个高级函数的知识. 一个函数可以接收另一个函数作为参数,这种函数就称之为高阶函数. def add(x, y, f): return f(x) + f(y) 当我们调用add(-, , abs ...

  7. Python函数式编程——map()、reduce()

    文章来源:http://www.pythoner.com/46.html 提起map和reduce想必大家并不陌生,Google公司2003年提出了一个名为MapReduce的编程模型[1],用于处理 ...

  8. (转)Python函数式编程——map()、reduce()

    转自:http://www.jianshu.com/p/7fe3408e6048 1.map(func,seq1[,seq2...]) Python 函数式编程中的map()函数是将func作用于se ...

  9. Python 函数式编程 & Python中的高阶函数map reduce filter 和sorted

    1. 函数式编程 1)概念 函数式编程是一种编程模型,他将计算机运算看做是数学中函数的计算,并且避免了状态以及变量的概念.wiki 我们知道,对象是面向对象的第一型,那么函数式编程也是一样,函数是函数 ...

随机推荐

  1. 新浪微博资深大牛全方位剖析 iOS 高级面试

    第1章 课程简介本章对这门课程所讲述内容进行概要介绍,其中包括课程目标.适合人群,课程特色.课程收获.课程安排等.整个课程学习完结后,有机会获得电话模拟面试及内推. 1-1 课前必读(不看会错过一个亿 ...

  2. 【转】打包2个10g文件 测试

    微博上kevin_prajna提了一个问题:“求Linux下一打包工具,需求:能把两个10G的文件打包成一个文件,时间在1分钟之内能接受!”. 暂且作答一下吧.首先问题是求解工具,那么我们忽略IO问题 ...

  3. C中typedef 函数指针的使用

    类型定义的语法可以归结为一句话:只要在变量定义前面加上typedef,就成了类型定义.这儿的原本应该是变量的东西,就成为了类型. int integer;     //整型变量int *pointer ...

  4. 关于lora标配SPDT大功率射频开关

    SPDT大功率的UltraCMOS ™DC - 3.0 GHz射频开关              PE4259的UltraCMOS ™射频开关被设计为覆盖广泛的,通过3000兆赫从近DC应用.这种反射 ...

  5. Spring事务(三)事务增强器

    摘要: 本文结合<Spring源码深度解析>来分析Spring 5.0.6版本的源代码.若有描述错误之处,欢迎指正. 目录 一.创建事务 1. 获取事务 2. 处理已经存在的事务 3. 准 ...

  6. POJ3268(Dijkstra_邻接矩阵)

    https://vjudge.net/problem/POJ-3268 题目大意: n个农场的n头奶牛将前往x农场,要选择一条来回时间最短的路径. (一头牛的返回路线可能不同于她最初去派对的路线,因为 ...

  7. CentOS中用Nexus搭建maven私服,为Hadoop编译提供本地镜像

    系统: CentOS release 6.6 (Final) Nexus:nexus-2.8.1-bundle.tar.gz,下载地址:https://sonatype-download.global ...

  8. 【题解】洛谷P1169 [ZJOI2007] 棋盘制作(坐标DP+悬线法)

    次元传送门:洛谷P1169 思路 浙江省选果然不一般 用到一个从来没有听过的算法 悬线法: 所谓悬线法 就是用一条线(长度任意)在矩阵中判断这条线能到达的最左边和最右边及这条线的长度 即可得到这个矩阵 ...

  9. U盘安装咱中国人自己的操作系统UbuntuKylin14.04LST(超具体原创图文教程)

    本文仅供參考,在准备级安装过程中出现的一切意外情况均与本文作者无关!原创教程转载请注明原转载地!系统简单介绍:UbuntuKylin 是Ubuntu官方认可的衍生版,其宗旨是创建一个Ubuntu的中文 ...

  10. better-scroll之吸顶效果巨坑挣扎中

    今天和大家分享下better-scroll这款移动端用来解决各种滚动需求的插件(目前已经支持PC) 关于其中的API大家可以去官网看下  这里就给大家介绍几种常用的以及需要注意的点是什么 首先说一下b ...