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 相关文章推荐
简单讲解Python中的字符串与字符串的输入输出
Mar 13 Python
Python对象类型及其运算方法(详解)
Jul 05 Python
python进阶之多线程对同一个全局变量的处理方法
Nov 09 Python
Python中函数参数匹配模型详解
Jun 09 Python
详解python编译器和解释器的区别
Jun 24 Python
Python-接口开发入门解析
Aug 01 Python
python的scipy实现插值的示例代码
Nov 12 Python
Python中os模块功能与用法详解
Feb 26 Python
详解基于Jupyter notebooks采用sklearn库实现多元回归方程编程
Mar 25 Python
自定义Django_rest_framework_jwt登陆错误返回的解决
Oct 18 Python
python 图像增强算法实现详解
Jan 24 Python
对PyTorch中inplace字段的全面理解
May 22 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
一个改进的UBB类
2006/10/09 PHP
PHP+Mysql分布式事务与解决方案深入理解
2021/02/27 PHP
JS类定义原型方法的两种实现的区别评论很多
2007/09/12 Javascript
一步一步制作jquery插件Tabs实现过程
2010/07/06 Javascript
图片动画横条广告带上下滚动的JS代码
2013/10/25 Javascript
Bootstrap富文本组件wysiwyg数据保存到mysql的方法
2016/05/09 Javascript
基于Vue el-autocomplete 实现类似百度搜索框功能
2019/10/25 Javascript
如何在Node和浏览器控制台中打印彩色文字
2020/01/09 Javascript
JavaScript缺少insertAfter解决方案
2020/07/03 Javascript
[10:14]2018DOTA2国际邀请赛寻真——paiN Gaming不仅为自己而战
2018/08/14 DOTA
Python实现豆瓣图片下载的方法
2015/05/25 Python
深入浅出学习python装饰器
2017/09/29 Python
利用TensorFlow训练简单的二分类神经网络模型的方法
2018/03/05 Python
pandas数据预处理之dataframe的groupby操作方法
2018/04/13 Python
Python实现 PS 图像调整中的亮度调整
2019/06/28 Python
Python正则表达式匹配日期与时间的方法
2019/07/07 Python
python实现多线程端口扫描
2019/08/31 Python
python 使用while写猜年龄小游戏过程解析
2019/10/07 Python
使用IDLE的Python shell窗口实例详解
2019/11/19 Python
python中如何进行连乘计算
2020/05/28 Python
Python pexpect模块及shell脚本except原理解析
2020/08/03 Python
CSS3 transforms应用于背景图像的解决方法
2019/04/16 HTML / CSS
美国经典刺绣和字母儿童服装特卖:Smocked Auctions
2018/07/16 全球购物
Intersport西班牙:在线体育商店
2019/11/06 全球购物
家乐福台湾线上购物网:Carrefour台湾
2020/09/15 全球购物
国际贸易个人求职信范文
2014/01/04 职场文书
实习鉴定评语
2014/01/19 职场文书
《我要的是葫芦》教学反思
2014/02/23 职场文书
模特职业生涯规划范文
2014/02/26 职场文书
2014年电信员工工作总结
2014/12/19 职场文书
通报表扬范文
2015/01/17 职场文书
医者仁心观后感
2015/06/17 职场文书
《平移和旋转》教学反思
2016/02/19 职场文书
Go语言中break label与goto label的区别
2021/04/28 Golang
如何用JavaScript学习算法复杂度
2021/04/30 Javascript
阿里云服务器(windows)手动部署FTP站点详细教程
2022/08/05 Servers