Python 2 与 Python 3 - 三个参数的映射行为有何差异?

标签 python python-3.x python-2.x

以下代码在 Python 2 和 Python 3 中的行为有所不同:

all(map(lambda x,y: x, [1, 2], [1, 2, 3]))

Python 2 给出False,而Python 3 给出Truedocumentation对于 Python 2 来说,如果较短的列表用尽,它将提供 None,但 Python 3 doesn't这样做。

我正在编写一个由于某种原因确实需要保持长度的代码。获得旧行为的最干净的方法是什么?我知道我可以使用 from past.builtin import map as old_map,但是有没有更优雅的解决方案可以在这两个版本中使用?

最佳答案

本质上,带有多个可迭代对象的map参数将zip可迭代对象,然后使用zip中的元组调用该函数,如下所示: var-args。因此,您可以使用 itertools.starmap 获得相同的行为和zip:

>>> a = [10, 20]
>>> b = [1, 2, 3]
>>> f = lambda x, y: x
>>> list(map(f, a, b))
[10, 20]
>>> from itertools import starmap
>>> list(starmap(f, zip(a, b)))
[10, 20]

然后可以通过将 zip 替换为 itertools.zip_longest 来实现您想要的行为:

>>> from itertools import starmap, zip_longest
>>> list(starmap(f, zip_longest(a, b)))
[10, 20, None]

来自 itertools 的两个函数也存在于 Python 2 中,只不过第二个函数名为 izip_longest反而。您只需 import ... as ... 即可解决这个问题。

关于Python 2 与 Python 3 - 三个参数的映射行为有何差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60532658/

相关文章:

python - 如何使用反斜杠 x\x 代码解码 ascii 字符串

Python IDLE 卡住

python - 多处理不工作(oserror :[Errno 22] Invalid argument )

python - Conda 软件包的完整性是否得到验证?

python - 如何使用 numpy 轻松从二维矩阵中获取这些值?

python - 类型错误 : super() takes at least 1 argument (0 given) error is specific to any python version?

python - 父访问在 Python 中子定义的类变量?

python 3 : When is a call to an instance attribute resolved as if it is an instance method?

Python:如何格式化循环以提取字典列表中的特定值?

python - python中的深度复制和字典更新