python - 如何在 Python 3 中使用过滤器、映射和归约

标签 python python-3.x filter functional-programming reduce

filtermapreduce 在 Python 2 中完美运行。下面是一个示例:

>>> def f(x):
        return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]

>>> def cube(x):
        return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

>>> def add(x,y):
        return x+y
>>> reduce(add, range(1, 11))
55

但在 Python 3 中,我收到以下输出:

>>> filter(f, range(2, 25))
<filter object at 0x0000000002C14908>

>>> map(cube, range(1, 11))
<map object at 0x0000000002C82B70>

>>> reduce(add, range(1, 11))
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    reduce(add, range(1, 11))
NameError: name 'reduce' is not defined

如果有人能向我解释为什么会这样,我将不胜感激。

代码截图更清楚:

IDLE sessions of Python 2 and 3 side-by-side

最佳答案

您可以阅读 What's New In Python 3.0 中的更改。 .当您从 2.x 迁移到 3.x 时,您应该仔细阅读它,因为已经发生了很多变化。

这里的全部答案是从文档中引用的。

Views And Iterators Instead Of Lists

Some well-known APIs no longer return lists:

  • [...]
  • map() and filter() return iterators. If you really need a list, a quick fix is e.g. list(map(...)), but a better fix is often to use a list comprehension (especially when the original code uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).
  • [...]

Builtins

  • [...]
  • Removed reduce(). Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.
  • [...]

关于python - 如何在 Python 3 中使用过滤器、映射和归约,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13638898/

相关文章:

python - Pandas:转换一系列时间戳,仅保留 YYYY-MM-DD 格式

python - 正则表达式检查日期

python-3.x - Pandas 日期时间问题 : How to Insert missing weekends into an existing dates column in a dataframe in python

python - 创建另一个模型时创建组

java - Hibernate 过滤器可以与条件查询一起使用吗?

python - QTextBrowser点击文本改变字体

python - 找到一个集合的子集,创建一个平衡的值(value)集

python - 非常大的矩阵向量积

html - 过滤 HTML 表格

r - 按三个条件中的两个过滤行