Python中的map、reduce和filter浅析


Posted in Python onApril 26, 2014

1、先看看什么是 iterable 对象

以内置的max函数为例子,查看其doc:

>>> print max.__doc__
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.

在max函数的第一种形式中,其第一个参数是一个 iterable 对象,既然这样,那么哪些是 iterable 对象呢?
>>> max('abcx')
>>> 'x'
>>> max('1234')
>>> '4'
>>> max((1,2,3))
>>> 3
>>> max([1,2,4])
>>> 4

我们可以使用yield生成一个iterable 对象(也有其他的方式):
def my_range(start,end):
    ''' '''
    while start <= end:
        yield start
        start += 1

执行下面的代码:
for num in my_range(1, 4):
    print num
print max(my_range(1, 4))

将输出:
1
2
3
4
4

2、map

在http://docs.python.org/2/library/functions.html#map中如此介绍map函数:

map(function, iterable, ...)
Apply function to every item of iterable and return a list of 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. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

map函数使用自定义的function处理iterable中的每一个元素,将所有的处理结果以list的形式返回。例如:
def func(x):
    ''' '''
    return x*x
print map(func, [1,2,4,8])
print map(func, my_range(1, 4))

运行结果是:
[1, 4, 16, 64]
[1, 4, 9, 16]

也可以通过列表推导来实现:
print [x*x for x in [1,2,4,8]]

3、reduce

在http://docs.python.org/2/library/functions.html#reduce中如下介绍reduce函数:

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

这个已经介绍的很明了,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])

相当于计算
((((1+2)+3)+4)+5)

而:
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5],6)

相当于计算
(((((6+1)+2)+3)+4)+5)

4、filter

在http://docs.python.org/2/library/functions.html#filter中如下介绍filter函数:

filter(function, iterable)
Construct a list 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 iterable is a string or a tuple, the result also has that type; otherwise it is always a list. 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 [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.

参数function(是函数)用于处理iterable中的每个元素,如果function处理某元素时候返回true,那么该元素将作为list的成员而返回。比如,过滤掉字符串中的字符a:
def func(x):
    ''' '''
    return x != 'a'
print filter(func, 'awake')

运行结果是:
wke

这也可以通过列表推导来实现:
print ''.join([x for x in 'awake' if x != 'a'])
Python 相关文章推荐
Hadoop中的Python框架的使用指南
Apr 22 Python
Python的Bottle框架中实现最基本的get和post的方法的教程
Apr 30 Python
python基于twisted框架编写简单聊天室
Jan 02 Python
Python cookbook(数据结构与算法)对切片命名清除索引的方法
Mar 13 Python
python3使用matplotlib绘制散点图
Mar 19 Python
Python数据类型之Dict字典实例详解
May 07 Python
Python转换时间的图文方法
Jul 01 Python
CentOS7下安装python3.6.8的教程详解
Jan 03 Python
python实现连连看游戏
Feb 14 Python
Python figure参数及subplot子图绘制代码
Apr 18 Python
Pymysql实现往表中插入数据过程解析
Jun 02 Python
如何用 Python 制作一个迷宫游戏
Feb 25 Python
Python实现的Kmeans++算法实例
Apr 26 #Python
爬山算法简介和Python实现实例
Apr 26 #Python
Python操作sqlite3快速、安全插入数据(防注入)的实例
Apr 26 #Python
python实现的二叉树算法和kmp算法实例
Apr 25 #Python
python中的__init__ 、__new__、__call__小结
Apr 25 #Python
Python yield 小结和实例
Apr 25 #Python
python计数排序和基数排序算法实例
Apr 25 #Python
You might like
PHP生成excel时单元格内换行问题的解决方法
2010/08/26 PHP
PHP容易忘记的知识点分享
2013/04/30 PHP
php去除换行(回车换行)的三种方法
2014/03/26 PHP
PHP tp5中使用原生sql查询代码实例
2020/10/28 PHP
学习JS面向对象成果 借国庆发布个最新作品与大家交流
2009/10/03 Javascript
Jquery之美中不足小结
2011/02/16 Javascript
CodeMirror2 IE7/IE8 下面未知运行时错误的解决方法
2012/03/29 Javascript
自己实现string的substring方法 人民币小写转大写,数字反转,正则优化
2012/09/02 Javascript
JQuery筛选器全系列介绍
2013/08/27 Javascript
jquery实现无限分级横向导航菜单的方法
2015/03/12 Javascript
JavaScript中的toLocaleLowerCase()方法使用详解
2015/06/06 Javascript
详解参数传递四种形式
2015/07/21 Javascript
小议JavaScript中Generator和Iterator的使用
2015/07/29 Javascript
jQuery实现可关闭固定于底(顶)部的工具条菜单效果
2015/11/06 Javascript
AngularJs表单验证实例代码解析
2016/11/29 Javascript
node.js 和HTML5开发本地桌面应用程序
2016/12/13 Javascript
bootstrap提示标签、提示框实现代码
2016/12/28 Javascript
JavaScript手风琴页面制作
2017/05/17 Javascript
详解webpack的配置文件entry与output
2017/08/21 Javascript
React Native自定义控件底部抽屉菜单的示例
2018/02/08 Javascript
手动用webpack搭建第一个ReactApp的示例
2018/04/11 Javascript
NodeJs 文件系统操作模块fs使用方法详解
2018/11/26 NodeJs
JavaScript适配器模式原理与用法实例详解
2020/03/09 Javascript
JS实现炫酷雪花飘落效果
2020/08/19 Javascript
python将字符串转换成数组的方法
2015/04/29 Python
python在一个范围内取随机数的简单实例
2020/08/16 Python
如何查看在weblogic中已经发布的EJB
2012/06/01 面试题
品管员岗位职责
2013/11/10 职场文书
大学生饮食配送创业计划书
2014/01/04 职场文书
竞争上岗实施方案
2014/03/21 职场文书
初中英语课后反思
2014/04/25 职场文书
教师群众路线教育实践活动个人对照检查材料
2014/11/04 职场文书
夫妻分居协议书范文
2014/11/26 职场文书
2014年幼儿园班级工作总结
2014/12/17 职场文书
学雷锋活动简报
2015/07/20 职场文书
详解盒子端CSS动画性能提升
2021/05/24 HTML / CSS