Python 的 map
可以采用多个可迭代对象,当可调用对象可以接受相同数量的输入参数时使用。如果输入可迭代对象的长度相同,则其行为类似于传递压缩参数的列表理解,例如:
>>> iterables = 'spam', 'eggs'
>>> map(max, *iterables)
['s', 'p', 'g', 's']
>>> [max(*a) for a in zip(*iterables)]
['s', 'p', 'g', 's']
当输入参数的长度不同时,情况会变得很奇怪 - Python 2 ( docs ) 用 None
填充,但 Python 3 ( docs ) 会截断为最短可迭代。
>>> map(max, 'spam', 'potato') # 2.x
['s', 'p', 't', 'm', 't', 'o']
>>> list(map(max, 'spam', 'potato')) # 3.x
['s', 'p', 't', 'm']
为什么存在此功能,需要或有用的典型案例示例是什么?我对函数样式了解不多,我是否会错过与多个参数相关的 map
的一些强大优势? 3.x 中 API 更改的理由是什么?
最佳答案
关于为什么 map
在 python3 中被截断,这只是因为 python3 的 map
实际上是 itertools.imap
。文档说:
Like
map()
but stops when the shortest iterable is exhausted instead of filling inNone
for shorter iterables. The reason for the difference is that infinite iterator arguments are typically an error formap()
(because the output is fully evaluated) but represent a common and useful way of supplying arguments toimap()
.
截断允许您执行诸如 map(func, itertools.repeat(5), [1,2,3])
之类的操作,并无需担心地迭代结果。使用旧的 map
,这将是一个无限循环。
python3 中最重要的变化之一是,许多内置函数现在返回生成器而不是 list
,包括 map
和 zip
。这种“增加的懒惰”改变了这些函数的使用方式,从而改变了行为。
至于为什么人们会使用 python2 的多重迭代来映射
我不知道。当然,它是类似(在 python3 中)的快捷方式:
list(itertools.starmap(function, itertools.zip_longest(*iterables)))
这可能有一些极端情况的用法,但我从未见过它被使用。
可能大多数人甚至不知道 map
接受一系列可迭代对象。
因此,据我所知,使用多个参数并不会产生任何超能力。
至于为什么 map
出现在该语言中,那是因为 map
早在列表推导式之前就已经存在了。在列表推导之前,它对于构建列表非常有用。
它没有被删除是为了向后兼容,而且因为很多人实际上喜欢它,
尽管吉多did want to remove it .
要了解有关 map
、filter
和 reduce
以及其他功能方面的历史的更多信息,请阅读:The History of Python: Origins of Python's "Functional" Features
关于python - 使用具有多个参数的 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20646996/