Python 2 与 Python 3 - 具有三个参数的地图行为差异? [英] Python 2 vs Python 3 - Difference in map behavior with three arguments?
问题描述
以下代码在 Python 2 和 Python 3 中的行为不同:
The following code behaves differently in Python 2 vs Python 3:
all(map(lambda x,y: x, [1, 2], [1, 2, 3]))
Python 2 给出 False
而 Python 3 给出 True
.Python 2 的 文档 说它将提供 None
如果较短的列表已用尽但 Python 3 没有 这样做.
Python 2 gives False
whereas Python 3 gives True
. The documentation for Python 2 says that it will supply None
if the shorter list is exhausted but Python 3 doesn't do that.
我正在编写一个出于某种原因确实需要保持长度的代码.获得旧行为的最干净的方法是什么?我知道我可以使用 from past.builtin import map as old_map
,但是有没有更优雅的解决方案可以同时在两个版本中使用?
I am working on a code that really needs the length to be maintained for some reason. What is the cleanest way to get the old behavior? I know I can use from past.builtin import map as old_map
, but is there a more elegant solution that would work in both versions?
推荐答案
本质上,map
为参数设置多个可迭代对象将 zip
可迭代对象,然后调用函数将 zip
中的元组作为 var-args.因此,您可以使用 itertools.starmap<获得相同的行为/code>
和 zip
:
Essentially, map
with multiple iterables for the arguments will zip
the iterables, and then call the function with the tuples from the zip
as var-args. So, you can get the same behaviour using 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
:
Then the behaviour you want can be achieved by replacing zip
with 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 ...
来解决这个问题.
Both functions from itertools
also exist in Python 2, except the second one is named izip_longest
instead. You can just import ... as ...
to get around that.
这篇关于Python 2 与 Python 3 - 具有三个参数的地图行为差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!