reduce、map、filter 互相轉化

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章