Python 3 vs Python 2 map behavior

前端 未结 4 700
耶瑟儿~
耶瑟儿~ 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条回答
  • 2020-12-09 04:03

    itertools.zip_longest does what you want, with a more comprehensible name. :)

    0 讨论(0)
  • 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)]
    
    0 讨论(0)
  • 2020-12-09 04:26

    you can solve the problem like this: list(map(lambda x, y: (x, y),[1, 2, 3 ,4, 5], [6, 7, 8, 9, 10]))

    0 讨论(0)
  • 2020-12-09 04:30

    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)))
    
    0 讨论(0)
提交回复
热议问题