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

0 0
原创粉丝点击