为什么map在Python3中返回map对象而不是列表?

2024-04-29 10:21:45 发布

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

我对理解new language design of Python 3.x感兴趣。

在Python 2.7中,我非常喜欢函数map

Python 2.7.12
In[2]: map(lambda x: x+1, [1,2,3])
Out[2]: [2, 3, 4]

然而,在Python3.x中,情况发生了变化:

Python 3.5.1
In[2]: map(lambda x: x+1, [1,2,3])
Out[2]: <map at 0x4218390>

我知道怎么做,但我找不到为什么。为什么语言设计师会做出这样的选择,在我看来,这会带来很大的痛苦。这是为了迫使开发人员坚持列表理解吗?

在我看来,list可以自然地被认为是Functors;我一直被认为是这样想的:

fmap :: (a -> b) -> f a -> f b

Tags: oflambda函数in语言mapnew情况
3条回答

我认为当generator expressions也存在时,map仍然存在的原因是它可以接受多个循环并传递到函数中的迭代器参数:

>>> list(map(min, [1,2,3,4], [0,10,0,10]))
[0,2,0,4]

这比使用zip要简单得多:

>>> list(min(x, y) for x, y in zip([1,2,3,4], [0,10,0,10]))

否则,它不会在生成器表达式上添加任何内容。

因为它返回一个迭代器,所以省略了在内存中存储完整大小的列表。这样你就可以很容易地在将来重复它,而不会对记忆造成任何痛苦。可能你甚至不需要一个完整的清单,但它的一部分,直到你的条件达到。

你可以发现这个docs很有用,迭代器非常棒。

An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing it to the built-in function next()) return successive items in the stream. When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its __next__() method just raise StopIteration again. Iterators are required to have an __iter__() method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.

Guido回答了这个问题here:“因为创建一个列表只会浪费”。

他还说,正确的转换是使用正则的for循环。

map()从2转换为3可能不仅仅是在其周围粘贴list( )的简单情况。圭多还说:

“如果输入序列的长度不相等,map()将在最短序列的终止处停止。为了与Python 2.x中的map()完全兼容,还可以将序列包装在itertools.zip_longest()中,例如

map(func, *sequences)

变成

list(map(func, itertools.zip_longest(*sequences)))

“。”

相关问题 更多 >