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 相关文章推荐
在Django框架中伪造捕捉到的URLconf值的方法
Jul 18 Python
python sys,os,time模块的使用(包括时间格式的各种转换)
Apr 27 Python
Python中Numpy包的安装与使用方法简明教程
Jul 03 Python
Python实现端口检测的方法
Jul 24 Python
python使用Matplotlib画饼图
Sep 25 Python
python实现基于信息增益的决策树归纳
Dec 18 Python
python3.x提取中文的正则表达式示例代码
Jul 23 Python
Python自动化导出zabbix数据并发邮件脚本
Aug 16 Python
浅谈python多线程和多线程变量共享问题介绍
Apr 17 Python
python基本算法之实现归并排序(Merge sort)
Sep 01 Python
django数据模型中null和blank的区别说明
Sep 02 Python
Python3自带工具2to3.py 转换 Python2.x 代码到Python3的操作
Mar 03 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
wordpress之wp-settings.php
2007/08/17 PHP
ThinkPHP 404页面的设置方法
2015/01/14 PHP
[原创]PHP正则匹配中英文、数字及下划线的方法【用户名验证】
2017/08/01 PHP
php实现的mongoDB单例模式操作类
2018/01/20 PHP
Open and Print a Word Document
2007/06/15 Javascript
mysql输出数据赋给js变量报unterminated string literal错误原因
2010/05/22 Javascript
根据邮箱的域名跳转到相应的登录页面的代码
2012/02/27 Javascript
Javascript引用指针使用介绍
2012/11/07 Javascript
JQuery+DIV自定义滚动条样式的具体实现
2013/06/25 Javascript
jquery $.each() 使用小探
2013/08/23 Javascript
node.js中的fs.readdirSync方法使用说明
2014/12/17 Javascript
Flash图片上传组件 swfupload使用指南
2015/03/14 Javascript
jQuery语法小结(超实用)
2015/12/31 Javascript
使用bootstrap3开发响应式网站
2016/05/12 Javascript
iscroll碰到Select无法选择下拉刷新的解决办法
2016/05/21 Javascript
JS中BOM相关知识点总结(必看篇)
2016/11/22 Javascript
微信小程序 引用其他js文件实现代码
2017/02/22 Javascript
jQuery实现一个简单的验证码功能
2017/06/26 jQuery
vue 使用外部JS与调用原生API操作示例
2019/12/02 Javascript
Python 的 with 语句详解
2014/06/13 Python
详解Python中time()方法的使用的教程
2015/05/22 Python
Python爬虫实现(伪)球迷速成
2018/06/10 Python
对json字符串与python字符串的不同之处详解
2018/12/19 Python
基于Python+Appium实现京东双十一自动领金币功能
2019/10/31 Python
德国旅行、体验和活动的预订平台:Watado
2019/12/04 全球购物
杭州时比特电子有限公司SQL
2013/08/22 面试题
简述使用ftp进行文件传输时的两种登录方式?它们的区别是什么?常用的ftp文件传输命令是什么?
2016/11/20 面试题
读书小明星事迹材料
2014/05/03 职场文书
小学生自我评价100字(15篇)
2014/09/18 职场文书
党委领导班子整改方案
2014/09/30 职场文书
2014年英语教研组工作总结
2014/12/06 职场文书
2015年学生会主席工作总结
2015/04/21 职场文书
卫生保健工作总结2015
2015/05/18 职场文书
2015初一年级组工作总结
2015/07/24 职场文书
新学期家长寄语2016
2015/12/03 职场文书
详解GaussDB for MySQL性能优化
2021/05/18 MySQL