今天閱讀了關于Python函數式編程的系列文章,地址在這里:
http://m.survivalescaperooms.com/huxi/archive/2011/06/24/2089358.html
里面提到了四個內建迭代函數:reduce、map、filter、zip。其中zip是供同時迭代多個迭代器用的,這里就不討論了。主要討論剩下的三個。
我發現一個有意思的事情,就是剩下的三個函數,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:
1 #map as the base 2 3 def _reduce(func, iterable, init): 4 result = init 5 map(lambda x: result = func(result, x), iterable) 6 return result 7 8 def _filter(func, iterable): 9 lst= []10 map(lambda x: lst.append(x) if func(x), iterable)11 return lst
這個是基于filter去實現另外兩者:
1 #filter as the base 2 3 def _reduce(func, iterable, init): 4 result = init 5 filter(lambda x: result = func(result, x), iterable) 6 return result 7 8 def _map(func, iterable): 9 lst = []10 filter(lambda x: lst.append(func(x)), iterable)11 return lst
可以發現它們大同小異,不是很有意思。
新聞熱點
疑難解答