首页 > 解决方案 > Python 2 vs Python 3 - 三个参数的地图行为差异?

问题描述

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

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

Python 2 提供False,而 Python 3 提供True. Python 2的文档None说,如果较短的列表用完,它将提供,但 Python 3不这样做。

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

标签: pythonpython-3.xpython-2.x

解决方案


本质上,map参数的多个迭代将zip迭代,然后使用zipas var-args 中的元组调用函数。itertools.starmap因此,您可以使用and获得相同的行为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]

itertoolsPython 2 中也存在这两个函数,除了第二个被命名izip_longest。你可以import ... as ...解决这个问题。


推荐阅读