如何在Python 3中使用过滤,映射和归约 [英] How to use filter, map, and reduce in Python 3
本文介绍了如何在Python 3中使用过滤,映射和归约的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
filter
,map
和reduce
在Python 2中完美工作.这是一个示例:
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
但是在Python 3中,我收到以下输出:
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
一些著名的API不再返回列表:
Some well-known APIs no longer return lists:
- [...]
-
map()
和
- [...]
map()
andfilter()
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 ismap()
invoked for the side effects of the function; the correct transformation is to use a regularfor
loop (since creating a list would just be wasteful).- [...]
Builtins
- [...]
- 已删除
reduce()
.如果确实需要,请使用functools.reduce()
;但是,在99%的情况下,显式for
循环更易于阅读.- [...]
- [...]
- Removed
reduce()
. Usefunctools.reduce()
if you really need it; however, 99 percent of the time an explicitfor
loop is more readable.- [...]
这篇关于如何在Python 3中使用过滤,映射和归约的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文