相关疑难解决方法(0)

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

filter,map并且reduce在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
Run Code Online (Sandbox Code Playgroud)

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

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

>>> map(cube, range(1, 11))
<map object at 0x0000000002C82B70> …
Run Code Online (Sandbox Code Playgroud)

python reduce functional-programming filter python-3.x

292
推荐指数
5
解决办法
25万
查看次数

解决python 3 vs python 2中的map函数问题

我对使用python进行函数式编程感兴趣,并且正在阅读Mary Rose Cook的博客文章函数式编程的实用介绍

显然,它是用python 2编写的,如下所示:

name_lengths = map(len, ["Mary", "Isla", "Sam"])

print name_lengths
# => [4, 4, 3]
Run Code Online (Sandbox Code Playgroud)

在Python 3中产生以下结果:

<map object at 0x100b87a20>
Run Code Online (Sandbox Code Playgroud)

我有两个问题:

  1. 为什么会这样呢?
  2. 除了将地图对象转换为列表然后使用numpy之外,还有其他解决方案吗?

python functional-programming python-2.7 python-3.x

2
推荐指数
1
解决办法
760
查看次数