reduce、map、filter 互相转化
来源:互联网 发布:郑州网络推广 编辑:程序博客网 时间:2024/04/30 21:57
Python有一个有意思的事情,就是reduce、map和filter,三者可以相互转换。例如以reduce为基础,可以实现map和filter函数如下:
1 def _map(func, iterable):
2 return reduce(lambda lst, x: lst.append(func(x))or lst, iterable, [])
3
4 def _filter(func, iterable):
5 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
可以发现它们大同小异,不过很有意思。
转载地址: http://www.cnblogs.com/starstone/p/4809768.html
- reduce、map、filter 互相转化
- filter,map,reduce
- filter,map,reduce
- python:map filter reduce
- filter、map、reduce、lambda
- filter()map() reduce()
- python filter/map/reduce
- filter map reduce
- lambda(),map(),reduce(),filter()
- filter、map、reduce、lambda
- python map reduce filter
- Map,Filter和Reduce
- python map reduce filter
- map、filter、reduce函数
- python map reduce filter
- filter、map、reduce学习
- Map,Filter 和 Reduce
- python map,reduce,filter
- Ubuntu桌面生存指南
- 网络游戏中使用促销码
- 指向指针的引用的实例解说
- shell脚本如何获取当前时间
- solr提交示例数据到索引库
- reduce、map、filter 互相转化
- 接口和抽象类的区别
- 全文检索引擎Solr系列
- hdu5438邻接表+topsprt+并查集
- koa 文件下载
- Gradle 使用命令行操作Gradle
- Java Socket 与飞秋 通信
- Asynctask原理
- Maven学习总结(三)