Python一个有意思的地方:reduce、map、filter
2015-09-15 11:36
666 查看
今天阅读了关于Python函数式编程的系列文章,地址在这里:
http://www.cnblogs.com/huxi/archive/2011/06/24/2089358.html
里面提到了四个内建迭代函数:reduce、map、filter、zip。其中zip是供同时迭代多个迭代器用的,这里就不讨论了。主要讨论剩下的三个。
我发现一个有意思的事情,就是剩下的三个函数,reduce、map和filter,三者可以相互转换。例如以reduce为基础,可以实现map和filter函数如下:
上面的or操作符是用作流程控制的, lst.append(x) or lst 会将x添加到lst中去, 然后返回lst,因为lst.append(x)会返回None。
基于map或filter去实现其他的函数也是可以的,只不过它们都不像基于reduce实现的map和filter那样简洁。贴出实现如下:
这个是基于map去实现reduce和filter:
这个是基于filter去实现另外两者:
可以发现它们大同小异,不是很有意思。
http://www.cnblogs.com/huxi/archive/2011/06/24/2089358.html
里面提到了四个内建迭代函数:reduce、map、filter、zip。其中zip是供同时迭代多个迭代器用的,这里就不讨论了。主要讨论剩下的三个。
我发现一个有意思的事情,就是剩下的三个函数,reduce、map和filter,三者可以相互转换。例如以reduce为基础,可以实现map和filter函数如下:
def _map(func, iterable): return reduce(lambda lst, x: lst.append(func(x)) or lst, iterable, []) def _filter(func, iterable): return reduce(lambda lst, x: lst.append(x) or lst if func(x) else lst, iterable, [])
上面的or操作符是用作流程控制的, lst.append(x) or lst 会将x添加到lst中去, 然后返回lst,因为lst.append(x)会返回None。
基于map或filter去实现其他的函数也是可以的,只不过它们都不像基于reduce实现的map和filter那样简洁。贴出实现如下:
这个是基于map去实现reduce和filter:
#map as the base def _reduce(func, iterable, init): result = init map(lambda x: result = func(result, x), iterable) return result def _filter(func, iterable): lst= [] map(lambda x: lst.append(x) if func(x), iterable) return lst
这个是基于filter去实现另外两者:
#filter as the base def _reduce(func, iterable, init): result = init filter(lambda x: result = func(result, x), iterable) return result def _map(func, iterable): lst = [] filter(lambda x: lst.append(func(x)), iterable) return lst
可以发现它们大同小异,不是很有意思。
相关文章推荐
- 使用python将ppm格式转换成jpg
- python程序运行时间
- 不错的python中级电子书
- alembic 使用
- 转:python命令行解析工具Argparse
- python核心编程第5章课后题答案
- python 文件获取绝对路径
- ipython notebook 浏览器中编写数学公式和现实
- python decimal和fractions模块
- python中的gil是什么?
- python 一些有用的库
- python 插入排序
- python3.X爬虫-图片获取
- python random模块
- python or not python
- 使用python中的matplotlib进行绘图分析数据
- Python学习笔记(三)
- python之xpath爬虫
- Python二分查找详解
- Python安装PIL遇到‘Could not find a version that satisfies the requirement PIL’