Python 3 vs Python 2 map behavior

前端 未结 4 699
耶瑟儿~
耶瑟儿~ 2020-12-09 04:00

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:

4条回答
  •  -上瘾入骨i
    2020-12-09 04:04

    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)]
    

提交回复
热议问题