国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Python一個有意思的地方:reduce、map、filter

2019-11-14 17:00:43
字體:
來源:轉載
供稿:網友

今天閱讀了關于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

 

可以發現它們大同小異,不是很有意思。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 富裕县| 丹棱县| 客服| 石棉县| 余干县| 永定县| 海丰县| 博客| 南城县| 红原县| 蓬溪县| 喀喇沁旗| 张家川| 诏安县| 马鞍山市| 九江县| 咸宁市| 旬邑县| 莱西市| 嘉黎县| 祁连县| 新化县| 江山市| 天水市| 木兰县| 阿坝县| 三亚市| 湖口县| 湘潭市| 宝兴县| 肃北| 蒲城县| 永寿县| 宜州市| 浦县| 济宁市| 临西县| 古丈县| 唐河县| 穆棱市| 苍南县|