解决Python3与Python2中的映射函数问题

2024-06-16 14:26:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我对使用python进行函数式编程很感兴趣,我正在阅读Mary Rose Cook的博客文章A practical introduction to functional programming。在

显然,它是用python 2写成的:

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

print name_lengths
# => [4, 4, 3]

在Python 3中会产生这样的结果:

^{pr2}$

我有两个问题:

  1. 为什么会这样?在
  2. 除了converting the map object to a list and then use numpy,还有其他解决方案吗?在

Tags: to函数namemaplen编程文章programming
2条回答

为了补充@dhke的优秀回答(这段话太长了,不能发表评论),请这样想。您希望通过组合mapfilter等对列表执行多个转换。因此有两种方法可以考虑:

  1. 将第一个转换应用于整个列表,然后应用第二个转换,依此类推
  2. 将所有转换应用于列表的第一个元素,然后应用到第二个元素,依此类推

python3方法允许其中任何一种,而第二种方法在python2中不能写得那么简洁:您必须用for循环显式地迭代列表,并建立一个新的结果列表。在

如文件所述,在migration guide

In Python 2 map() returns a list while in Python 3 it returns an iterator.

Python 2

Apply function to every item of iterable and return a list of the results.

Python 3

Return an iterator that applies function to every item of iterable, yielding the results.

Python2总是执行list(imap(...))等效的操作,Python3允许延迟计算。在

相关问题 更多 >