以下代码在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
,但是还有一个更优雅的解决方案可以在两个版本中使用吗?
本质上,map
具有多个可迭代变量的参数将zip
可迭代变量,然后使用来自zip
的元组作为var-args调用该函数。因此,您可以使用itertools.starmap
和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