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 相关文章推荐
一则python3的简单爬虫代码
May 26 Python
python中遍历文件的3个方法
Sep 02 Python
分享Python文本生成二维码实例
Jan 06 Python
浅谈终端直接执行py文件,不需要python命令
Jan 23 Python
浅谈python函数之作用域(python3.5)
Oct 27 Python
Python对象属性自动更新操作示例
Jun 15 Python
Python numpy.array()生成相同元素数组的示例
Nov 12 Python
pyttsx3实现中文文字转语音的方法
Dec 24 Python
从numpy数组中取出满足条件的元素示例
Nov 26 Python
python针对Oracle常见查询操作实例分析
Apr 30 Python
python中JWT用户认证的实现
May 18 Python
Python文件操作模拟用户登陆代码实例
Jun 09 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 AJAX实例根据邮编自动完成地址信息
2008/11/23 PHP
PHP+MySQL 制作简单的留言本
2009/11/02 PHP
PHP sprintf()函数用例解析
2011/05/18 PHP
新手菜鸟必读:session与cookie的区别
2013/08/22 PHP
PHP实现的简单日历类
2014/11/29 PHP
详解PHP中的外观模式facade pattern
2018/02/05 PHP
用于table内容排序
2006/07/21 Javascript
javascript中定义类的方法汇总
2014/12/28 Javascript
jQuery学习笔记之jQuery+CSS3的浏览器兼容性
2015/01/19 Javascript
node.js版本管理工具n无效的原理和解决方法
2016/11/24 Javascript
swiper 自动图片无限轮播实现代码
2018/05/21 Javascript
angularjs 动态从后台获取下拉框的值方法
2018/08/13 Javascript
Vue.js点击切换按钮改变内容的实例讲解
2018/08/22 Javascript
Nodejs实现多文件夹文件同步
2018/10/17 NodeJs
使用JavaScrip模拟实现仿京东搜索框功能
2019/10/16 Javascript
[01:35]辉夜杯战队访谈宣传片—iG.V
2015/12/25 DOTA
Python实现Logger打印功能的方法详解
2017/09/01 Python
Python列表删除的三种方法代码分享
2017/10/31 Python
Python实现自动发送邮件功能
2021/03/02 Python
解决pyqt5中QToolButton无法使用的问题
2019/06/21 Python
python实现简易淘宝购物
2019/11/22 Python
在 Linux/Mac 下为Python函数添加超时时间的方法
2020/02/20 Python
Python 防止死锁的方法
2020/07/29 Python
如何用Matlab和Python读取Netcdf文件
2021/02/19 Python
Python实现图片指定位置加图片水印(附Pyinstaller打包exe)
2021/03/04 Python
如何使用amaze ui的分页样式封装一个通用的JS分页控件
2020/08/21 HTML / CSS
什么是命名空间(NameSpace)
2015/11/24 面试题
保安自我鉴定范文
2013/12/08 职场文书
财务管理职业生涯规划范文
2013/12/27 职场文书
会计电算化大学生职业规划书
2014/02/05 职场文书
商场中秋节活动方案
2014/02/07 职场文书
新年寄语大全
2014/04/12 职场文书
银行职员自我鉴定
2014/04/20 职场文书
电台编导求职信
2014/05/06 职场文书
作风转变年心得体会
2014/10/22 职场文书
如何开发一个渐进式Web应用程序PWA
2021/05/10 Javascript