gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:41:59 24 4
gpt4 key购买 nike

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 的多重迭代来 map 我不知道。当然,它是类似(在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com