这是我习惯于在Python 2中使用的filter
,map
和reduce
的方式:
>>> 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
为什么结果不同?我该如何让Python 3代码像Python 2代码一样工作?
另请参阅:reduce()有什么问题?,以了解将
reduce
放入标准库模块而不是保留为内置函数的具体动机。