In Python 2, a common (old, legacy) idiom is to use map
to join iterators of uneven length using the form map(None,iter,iter,...)
like so:
itertools.zip_longest does what you want, with a more comprehensible name. :)
I'll answer my own question this time.
With Python 3x, you can use itertools.zip_longest like so:
>>> list(map(lambda *a: a,*zip(*itertools.zip_longest(range(5),range(10,17)))))
[(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (None, 15), (None, 16)]
You can also roll ur own I suppose:
>>> def oldMapNone(*ells):
... '''replace for map(None, ....), invalid in 3.0 :-( '''
... lgst = max([len(e) for e in ells])
... return list(zip(* [list(e) + [None] * (lgst - len(e)) for e in ells]))
...
>>> oldMapNone(range(5),range(10,12),range(30,38))
[(0, 10, 30), (1, 11, 31), (2, None, 32), (3, None, 33), (4, None, 34), (None, None, 35), (None, None, 36), (None, None, 37)]
you can solve the problem like this:
list(map(lambda x, y: (x, y),[1, 2, 3 ,4, 5], [6, 7, 8, 9, 10]))
One way if you need some obsolete functionality in from the Python 2 then one way - write it yourself. Of course, it's not built-in functionality, but at least it is something.
The code snippet below takes 27 lines
#!/usr/bin/env python3
def fetch(sequence, index):
return None if len(sequence) <= index else sequence[index]
def mymap(f, *args):
max_len = 0
for i in range(len(args)):
max_len = max(max_len, len(args[i]))
out = []
for i in range(max_len):
t = []
for j in range(len(args)):
t.append(fetch(args[j],i))
if f != None:
# Use * for unpack arguments from Arbitarily argument list
# Use ** for unpack arguments from Keyword argument list
out.append(f(*t))
else:
out.append(tuple(t))
return out
if __name__ == '__main__':
print(mymap(None, [1,2,3,4,5],[2,1,3,4],[3,4]))
print(mymap(None,range(5),range(10,12)))