Python 2 Vs Python 3 - Difference In Map Behavior With Three Arguments?
The following code behaves differently in Python 2 vs Python 3: all(map(lambda x,y: x, [1, 2], [1, 2, 3])) Python 2 gives False whereas Python 3 gives True. The documentation for
Solution 1:
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]
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]
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.
Post a Comment for "Python 2 Vs Python 3 - Difference In Map Behavior With Three Arguments?"