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中threading超线程用法实例分析
May 16 Python
python中管道用法入门实例
Jun 04 Python
python中使用xlrd读excel使用xlwt写excel的实例代码
Jan 31 Python
python实现人脸识别经典算法(一) 特征脸法
Mar 13 Python
Python语言检测模块langid和langdetect的使用实例
Feb 19 Python
python如何解析配置文件并应用到项目中
Jun 27 Python
python 执行终端/控制台命令的例子
Jul 12 Python
python PyQt5/Pyside2 按钮右击菜单实例代码
Aug 17 Python
深入浅析Python 中的sklearn模型选择
Oct 12 Python
经验丰富程序员才知道的8种高级Python技巧
Jul 27 Python
Python文件的操作示例的详细讲解
Apr 08 Python
利用For循环遍历Python字典的三种方法实例
Mar 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快速url重写 更新版[需php 5.30以上]
2010/04/20 PHP
ThinkPHP分组下自定义标签库实例
2014/11/01 PHP
分享一个Laravel好用的Cache宏
2015/03/02 PHP
php 流程控制switch的简单实例
2016/06/07 PHP
php使用gd2绘制基本图形示例(直线、圆、正方形)
2017/02/15 PHP
jQuery基础框架浅入剖析
2012/12/27 Javascript
三分钟带你玩转jQuery.noConflict()
2016/02/15 Javascript
js中常用的Tab切换效果(推荐)
2016/08/30 Javascript
原生Javascript插件开发实践
2017/01/09 Javascript
jQuery使用方法
2017/02/04 Javascript
Angular.JS实现无限级的联动菜单(使用demo)
2017/02/08 Javascript
Vue2.0利用 v-model 实现组件props双向绑定的优美解决方案
2017/03/13 Javascript
Webpack执行命令参数详解
2017/06/17 Javascript
p5.js入门教程和基本形状绘制
2018/03/15 Javascript
详解jQuery设置内容和属性
2019/04/11 jQuery
JS箭头函数和常规函数之间的区别实例分析【 5 个区别】
2020/05/27 Javascript
[00:02]DOTA2新版本使用PA至宝后暴击展示
2014/11/19 DOTA
[01:04:06]DOTA2上海特级锦标赛A组资格赛#2 Secret VS EHOME第一局
2016/02/26 DOTA
Numpy array数据的增、删、改、查实例
2018/06/04 Python
对Python 获取类的成员变量及临时变量的方法详解
2019/01/22 Python
Python3内置模块pprint让打印比print更美观详解
2019/06/02 Python
Python中的支持向量机SVM的使用(附实例代码)
2019/06/26 Python
wxpython多线程防假死与线程间传递消息实例详解
2019/12/13 Python
mac 上配置Pycharm连接远程服务器并实现使用远程服务器Python解释器的方法
2020/03/19 Python
浅析PyCharm 的初始设置(知道)
2020/10/12 Python
CSS3实现大小不一的粒子旋转加载动画
2016/04/21 HTML / CSS
美国网上眼镜商城:Zenni Optical
2016/11/20 全球购物
YSL Beauty加拿大官方商城:圣罗兰美妆加拿大
2017/05/15 全球购物
大学毕业的自我鉴定
2013/10/08 职场文书
企业管理毕业生求职信范文
2014/03/07 职场文书
工伤事故赔偿协议书(标准)
2014/09/29 职场文书
单身证明范本
2015/06/15 职场文书
2016关于学习党章的心得体会
2016/01/15 职场文书
《云雀的心愿》教学反思
2016/02/23 职场文书
创业计划书之牛肉汤快餐店
2019/10/08 职场文书
深入理解Vue的数据响应式
2021/05/15 Vue.js