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

问题描述 投票:0回答:1

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

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

[Python 2提供False,而Python 3提供True。 Python 2的documentation表示如果较短的列表用尽,它将提供None,但Python 3 doesn't会这样做。

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

python python-3.x python-2.x
1个回答
1
投票

本质上,map具有多个可迭代变量的参数将zip可迭代变量,然后使用来自zip的元组作为var-args调用该函数。因此,您可以使用itertools.starmapitertools.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
© www.soinside.com 2019 - 2024. All rights reserved.