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函数的周期性执行实现方法
Aug 13 Python
对python requests发送json格式数据的实例详解
Dec 19 Python
Python进阶之自定义对象实现切片功能
Jan 07 Python
Python3.6实现带有简单界面的有道翻译小程序
Apr 16 Python
Python实现html转换为pdf报告(生成pdf报告)功能示例
May 04 Python
python TF-IDF算法实现文本关键词提取
May 29 Python
Python pip替换为阿里源的方法步骤
Jul 02 Python
pandas计算最大连续间隔的方法
Jul 04 Python
Django中celery执行任务结果的保存方法
Jul 12 Python
浅谈Python线程的同步互斥与死锁
Mar 22 Python
keras自动编码器实现系列之卷积自动编码器操作
Jul 03 Python
python如何遍历指定路径下所有文件(按按照时间区间检索)
Sep 14 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一些有意思的小区别
2006/12/06 PHP
详解WordPress中简码格式标签编写的基本方法
2015/12/22 PHP
Joomla简单判断用户是否登录的方法
2016/05/04 PHP
CI框架实现cookie登陆的方法详解
2016/05/18 PHP
php实现的证件照换底色功能示例【人像抠图/换背景图】
2020/05/29 PHP
JQuery制作的放大效果的popup对话框(未添加任何jquery plugin)分享
2013/04/28 Javascript
jquery()函数的三种语法介绍
2013/10/09 Javascript
jquery获取当前元素索引值用法实例
2015/06/10 Javascript
jQuery中选择器的基础使用教程
2016/05/23 Javascript
Javascript使用function创建类的两种方法(推荐)
2016/11/19 Javascript
JS实现的DIV块来回滚动效果示例
2017/02/07 Javascript
详解Angular.js指令中scope类型的几种特殊情况
2017/02/21 Javascript
通过命令行生成vue项目框架的方法
2017/07/12 Javascript
JS实现去除数组中重复json的方法示例
2017/12/21 Javascript
使用vue 国际化i18n 实现多实现语言切换功能
2018/10/11 Javascript
Vue侦测相关api的实现方法
2019/05/22 Javascript
Js代码中的span拼接问题解决
2019/11/22 Javascript
python装饰器使用方法实例
2013/11/21 Python
django初始化数据库的实例
2018/05/27 Python
django实现类似触发器的功能
2019/11/15 Python
Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签
2019/12/04 Python
Python气泡提示与标签的实现
2020/04/01 Python
pandas使用之宽表变窄表的实现
2020/04/12 Python
selenium判断元素是否存在的两种方法小结
2020/12/07 Python
传统HTML页面实现模块化加载的方法
2018/10/15 HTML / CSS
Mytheresa美国官网:德国知名的女性奢侈品电商
2017/05/27 全球购物
澳大利亚冒险体验:Adrenaline(跳伞、V8赛车、热气球等)
2017/09/18 全球购物
Fox Racing官方网站:越野摩托车和山地自行车装备和服装
2019/12/23 全球购物
法律专业自我鉴定
2013/10/03 职场文书
上班睡觉检讨书
2014/01/09 职场文书
缓刑人员的思想汇报
2014/01/11 职场文书
教育科研先进个人材料
2014/01/26 职场文书
2014社区健康教育工作总结
2014/12/16 职场文书
国家助学金感谢信
2015/01/21 职场文书
导游词之阳朔遇龙河
2019/12/16 职场文书
浅谈Mysql多表连接查询的执行细节
2021/04/24 MySQL