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字符串处理函数简明总结
Apr 13 Python
python删除字符串中指定字符的方法
Aug 13 Python
Window 64位下python3.6.2环境搭建图文教程
Sep 19 Python
python实现几种归一化方法(Normalization Method)
Jul 31 Python
Tensorflow 多线程与多进程数据加载实例
Feb 05 Python
python GUI编程(Tkinter) 创建子窗口及在窗口上用图片绘图实例
Mar 04 Python
Python3自定义http/https请求拦截mitmproxy脚本实例
May 11 Python
Python基于BeautifulSoup爬取京东商品信息
Jun 01 Python
如何清空python的变量
Jul 05 Python
利用Python实现Json序列化库的方法步骤
Sep 09 Python
anaconda升级sklearn版本的实现方法
Feb 22 Python
忆童年!用Python实现愤怒的小鸟游戏
Jun 07 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静态调用非静态方法的应用分析
2013/05/02 PHP
thinkphp普通查询与表达式查询实例分析
2014/11/24 PHP
Laravel中注册Facades的步骤详解
2016/03/16 PHP
thinkphp3.x连接mysql数据库的方法(具体操作步骤)
2016/05/19 PHP
Javascript remove 自定义数组删除方法
2009/10/20 Javascript
jquery+json 通用三级联动下拉列表
2010/04/19 Javascript
Javascript(AJAX)解析XML的代码(兼容FIREFOX/IE)
2010/07/11 Javascript
jquery miniui 教程 表格控件 合并单元格应用
2012/11/25 Javascript
js 回车提交表单两种实现方法
2012/12/31 Javascript
IE8下String的Trim()方法失效的解决方法
2013/11/08 Javascript
js中函数调用的两种常用方法使用介绍
2014/07/17 Javascript
微信小程序 倒计时组件实现代码
2016/10/24 Javascript
获取select的value、text值的简单示例(jquery与javascript)
2016/12/07 Javascript
脚本div实现拖放功能(两种)
2017/02/13 Javascript
基于vue实现网站前台的权限管理(前后端分离实践)
2018/01/13 Javascript
vue单页缓存方案分析及实现
2018/09/25 Javascript
KOA+egg.js集成kafka消息队列的示例
2018/11/09 Javascript
小程序实现背景音乐播放和暂停
2020/06/19 Javascript
JavaScript实现点击切换验证码及校验
2021/01/10 Javascript
python的类变量和成员变量用法实例教程
2014/08/25 Python
python查询mysql中文乱码问题
2014/11/09 Python
Python实现一个简单的MySQL类
2015/01/07 Python
Python3.2中的字符串函数学习总结
2015/04/23 Python
实例讲解Python的函数闭包使用中应注意的问题
2016/06/20 Python
python爬虫中get和post方法介绍以及cookie作用
2018/02/08 Python
Python实现的微信支付方式总结【三种方式】
2019/04/13 Python
python pyinstaller打包exe报错的解决方法
2019/11/02 Python
检测浏览器是否支持html5视频的代码
2013/03/28 HTML / CSS
HTML5之消息通知的使用(Web Notification)
2018/10/30 HTML / CSS
移动端Html5中百度地图的点击事件
2019/01/31 HTML / CSS
彪马荷兰官网:PUMA荷兰
2019/05/08 全球购物
俄罗斯电子产品在线商店:UltraTrade
2020/01/30 全球购物
求职信格式要求
2014/05/23 职场文书
精神文明建设汇报材料
2014/12/24 职场文书
优秀工作者事迹材料
2014/12/26 职场文书
python利用pandas分析学生期末成绩实例代码
2021/07/09 Python