2024-06-16 14:26:19 发布
网友
我对使用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中会产生这样的结果:
我有两个问题:
为了补充@dhke的优秀回答(这段话太长了,不能发表评论),请这样想。您希望通过组合map、filter等对列表执行多个转换。因此有两种方法可以考虑:
map
filter
python3方法允许其中任何一种,而第二种方法在python2中不能写得那么简洁:您必须用for循环显式地迭代列表,并建立一个新的结果列表。在
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允许延迟计算。在
list(imap(...))
为了补充@dhke的优秀回答(这段话太长了,不能发表评论),请这样想。您希望通过组合
map
、filter
等对列表执行多个转换。因此有两种方法可以考虑:python3方法允许其中任何一种,而第二种方法在python2中不能写得那么简洁:您必须用
for
循环显式地迭代列表,并建立一个新的结果列表。在如文件所述,在migration guide
Python 2:
Python 3:
Python2总是执行
list(imap(...))
等效的操作,Python3允许延迟计算。在相关问题 更多 >
编程相关推荐