filter 和 map 合起來能做的事情,列表推導也可以做,而且還不需要借助難以理解和閱讀的 lambda 表達式。文章來源:http://www.zghlxwxcb.cn/news/detail-802299.html
>>> symbols = '$¢£¥€¤'
>>> beyond_ascii = [ord(s) for s in symbols if ord(s) > 127]
>>> beyond_ascii
[162, 163, 165, 8364, 164]
>>> beyond_ascii = list(filter(lambda c: c > 127, map(ord, symbols)))
>>> beyond_ascii
[162, 163, 165, 8364, 164]
我原以為 map/filter 組合起來用要比列表推導快一些,Alex Martelli 卻說不一定——至少在上面這個例子中不一定。在本書的代碼倉庫(https://github.com/fluentpython/examplecode)中有名為 02-array-seq/listcomp_speed.py(https://github.com/fluentpython/example-code/blob/master/02-array-seq/listcomp_speed.py)的腳本,代碼中有這兩個方法的效率的比較。文章來源地址http://www.zghlxwxcb.cn/news/detail-802299.html
到了這里,關于python 列表推導同filter和map的比較的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!