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中列表(list)操作方法汇总
Aug 18 Python
用Python给文本创立向量空间模型的教程
Apr 23 Python
python使用PIL缩放网络图片并保存的方法
Apr 24 Python
Python中使用装饰器来优化尾递归的示例
Jun 18 Python
python dict 字典 以及 赋值 引用的一些实例(详解)
Jan 20 Python
python 字符串转列表 list 出现\ufeff的解决方法
Jun 22 Python
浅析python实现scrapy定时执行爬虫
Mar 04 Python
python抓取京东小米8手机配置信息
Nov 13 Python
python实现共轭梯度法
Jul 03 Python
利用python实现PSO算法优化二元函数
Nov 13 Python
解决Numpy中sum函数求和结果维度的问题
Dec 06 Python
tensorflow的计算图总结
Jan 12 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
Chrome Web App开发小结
2014/09/04 PHP
浅谈PHP中output_buffering
2015/07/13 PHP
PHP实现可精确验证身份证号码的工具类示例
2018/05/31 PHP
thinkPHP框架动态配置用法实例分析
2018/06/14 PHP
laravel框架添加数据,显示数据,返回成功值的方法
2019/10/11 PHP
常见的原始JS选择器使用方法总结
2014/04/09 Javascript
JQuery控制div外点击隐藏而div内点击不会隐藏的方法
2015/01/13 Javascript
angular分页指令操作
2017/01/09 Javascript
Node.js编写CLI的实例详解
2017/05/17 Javascript
import与export在node.js中的使用详解
2017/09/28 Javascript
JavaScript简易计算器制作
2020/01/17 Javascript
vue 翻页组件vue-flip-page效果
2020/02/05 Javascript
JavaScript变量Dom对象的所有属性
2020/04/30 Javascript
使用py2exe在Windows下将Python程序转为exe文件
2016/03/04 Python
详谈python http长连接客户端
2017/06/12 Python
Flask框架URL管理操作示例【基于@app.route】
2018/07/23 Python
Python中实现单例模式的n种方式和原理
2018/11/14 Python
Python字符串的一些操作方法总结
2019/06/10 Python
Python实现获取系统临时目录及临时文件的方法示例
2019/06/26 Python
使用Python制作缩放自如的圣诞老人(圣诞树)
2019/12/25 Python
详解Python中pyautogui库的最全使用方法
2020/04/01 Python
python 中的9个实用技巧,助你提高开发效率
2020/08/30 Python
Python接口自动化测试框架运行原理及流程
2020/11/30 Python
LTD Commodities:礼品,独特发现,家居装饰,家用器皿
2017/08/11 全球购物
英国奢华护肤、美容和Spa品牌:Temple Spa
2019/11/02 全球购物
总裁秘书岗位职责
2013/12/04 职场文书
班级文化建设标语
2014/06/23 职场文书
大学生学雷锋活动总结
2014/06/26 职场文书
创建绿色学校先进个人材料
2014/08/20 职场文书
反四风对照检查材料
2014/09/22 职场文书
2015年清明节活动总结
2015/02/09 职场文书
农业项目投资意向书
2015/05/09 职场文书
大学文艺委员竞选稿
2015/11/19 职场文书
2016年最美孝心少年事迹材料
2016/02/26 职场文书
Java字符串逆序方法详情
2022/03/21 Java/Android
vue-cli3.0修改打包后的文件名和文件地址,打包后本地运行报错解决
2022/04/06 Vue.js