如何在Python 3中使用filter、map和reduce ?

百科知识2025-04-261

62  

The functionality of map and filter was intentionally changed to return iterators, and reduce was removed from being a built-in and placed in functools.reduce.

map和filter的功能被有意地更改为返回迭代器,并且reduce被从内置的功能中删除,并放置到function tools.reduce中。

So, for filter and map, you can wrap them with list() to see the results like you did before.

因此,对于filter和map,您可以使用list()将它们包装起来,以便像以前那样查看结果。

def f(x): return x % 2 != 0 and x % 3 != 0
...
list(filter(f, range(2, 25)))
[5, 7, 11, 13, 17, 19, 23]
def cube(x): return xxx
...
list(map(cube, range(1, 11)))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
import functools
def add(x,y): return x+y
...
functools.reduce(add, range(1, 11))
55

The recommendation now is that you replace your usage of map and filter with generators expressions or list comprehensions. Example:

现在的建议是使用生成器表达式或列表理解替换map和filter。例子:

def f(x): return x % 2 != 0 and x % 3 != 0
...
[i for i in range(2, 25) if f(i)]
[5, 7, 11, 13, 17, 19, 23]
def cube(x): return xxx
...
[cube(i) for i in range(1, 11)]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

They say that for loops are 99 percent of the time easier to read than reduce, but I'd just stick with functools.reduce.

他们说for循环有99%的时间更容易阅读而不是减少,但我还是坚持使用function工具。

Edit: The 99 percent figure is pulled directly from the What’s New In Python 3.0 page authored by Guido van Rossum.

编辑:99%的数字直接来自于由Guido van Rossum撰写的Python 3.0页面的新内容。