以下代码在 Python 2 和 Python 3 中的行为有所不同:
all(map(lambda x,y: x, [1, 2], [1, 2, 3]))
Python 2 给出False
,而Python 3 给出True
。 documentation对于 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/