如何在 Python 3 中使用过滤器、映射和缩减 [英] How to use filter, map, and reduce in Python 3

查看:27
本文介绍了如何在 Python 3 中使用过滤器、映射和缩减的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

filtermapreduce 在 Python 2 中完美运行.这是一个例子:

<预><代码>>>>定义 f(x):返回 x % 2 != 0 和 x % 3 != 0>>>过滤器(f,范围(2, 25))[5, 7, 11, 13, 17, 19, 23]>>>定义立方体(x):返回 x*x*x>>>地图(立方体,范围(1, 11))[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]>>>定义添加(x,y):返回 x+y>>>减少(添加,范围(1, 11))55

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

<预><代码>>>>过滤器(f,范围(2, 25))<过滤器对象在 0x0000000002C14908>>>>地图(立方体,范围(1, 11))<0x0000000002C82B70处的映射对象>>>>减少(添加,范围(1, 11))回溯(最近一次调用最后一次):文件<pyshell#8>",第 1 行,在 <module> 中减少(添加,范围(1, 11))NameError:未定义名称reduce"

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

为了更清晰的代码截图:

解决方案

您可以阅读 Python 3.0 中的新功能.当您从 2.x 迁移到 3.x 时,您应该仔细阅读它,因为发生了很多变化.

此处的全部答案均来自文档.

视图和迭代器而不是列表

<块引用>

一些著名的 API 不再返回列表:

  • [...]
  • map()filter() 返回迭代器.如果你真的需要一个列表,一个快速的解决方法是例如list(map(...)),但更好的解决方法通常是使用列表推导式(尤其是当原始代码使用 lambda 时),或者重写代码使其不需要列表根本.特别棘手的是 map() 为函数的副作用而调用;正确的转换是使用常规的 for 循环(因为创建列表只会浪费).
  • [...]

内置

<块引用>
  • [...]
  • 删除了reduce().使用 functools.reduce()如果你真的需要它;然而,在 99% 的情况下,显式 for 循环更具可读性.
  • [...]

filter, map, and reduce work perfectly in Python 2. Here is an example:

>>> 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

But in Python 3, I receive the following outputs:

>>> 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

I would appreciate if someone could explain to me why this is.

Screenshot of code for further clarity:

解决方案

You can read about the changes in What's New In Python 3.0. You should read it thoroughly when you move from 2.x to 3.x since a lot has been changed.

The whole answer here are quotes from the documentation.

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 3 中使用过滤器、映射和缩减的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆