python - 使用具有多个参数的 map

标签 python dictionary functional-programming

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 in None for shorter iterables. The reason for the difference is that infinite iterator arguments are typically an error for map() (because the output is fully evaluated) but represent a common and useful way of supplying arguments to imap().

截断允许您执行诸如 map(func, itertools.repeat(5), [1,2,3]) 之类的操作,并无需担心地迭代结果。使用旧的 map ,这将是一个无限循环。

python3 中最重要的变化之一是,许多内置函数现在返回生成器而不是 list,包括 mapzip。这种“增加的懒惰”改变了这些函数的使用方式,从而改变了行为。

至于为什么人们会使用 python2 的多重迭代来映射我不知道。当然,它是类似(在 python3 中)的快捷方式:

list(itertools.starmap(function, itertools.zip_longest(*iterables)))

这可能有一些极端情况的用法,但我从未见过它被使用。 可能大多数人甚至不知道 map 接受一系列可迭代对象。 因此,据我所知,使用多个参数并不会产生任何超能力。

至于为什么 map 出现在该语言中,那是因为 map 早在列表推导式之前就已经存在了。在列表推导之前,它对于构建列表非常有用。 它没有被删除是为了向后兼容,而且因为很多人实际上喜欢它, 尽管吉多did want to remove it .

要了解有关 mapfilterreduce 以及其他功能方面的历史的更多信息,请阅读:The History of Python: Origins of Python's "Functional" Features

关于python - 使用具有多个参数的 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20646996/

相关文章:

python - 在 Anaconda 中安装 Plotly

python - 如何使用 ImageDraw 模糊椭圆

javascript - Lodash:从对象中选择值列表到保证顺序的数组中

javascript - 使用折叠映射任意 n 元树

python matplotlib——重新生成图形?

python - 有没有一种更快的方法来创建空数组的元素数组而不使用 for 循环

r - 使用数据值(字典)。 R 中的数据帧和重新编码

python - 查找第二次出现的索引最小的第一个重复数字

php - 在列表中分组 - php

functional-programming - SML 中的组合函数