Zip with list output instead of tuple

前端 未结 7 2000
梦毁少年i
梦毁少年i 2020-12-07 12:57

What is the fastest and most elegant way of doing list of lists from two lists?

I have

In [1]: a=[1,2,3,4,5,6]

In [2]: b=[7,8,9,10,11,12]

In [3]: z         


        
相关标签:
7条回答
  • 2020-12-07 13:31

    You almost had the answer yourself. Don't use map instead of zip. Use map AND zip.

    You can use map along with zip for an elegant, functional approach:

    list(map(list, zip(a, b)))
    

    zip returns a list of tuples. map(list, [...]) calls list on each tuple in the list. list(map([...]) turns the map object into a readable list.

    0 讨论(0)
  • 2020-12-07 13:42

    I generally don't like using lambda, but...

    >>> a = [1, 2, 3, 4, 5]
    >>> b = [6, 7, 8, 9, 10]
    >>> c = lambda a, b: [list(c) for c in zip(a, b)]
    >>> c(a, b)
    [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
    

    If you need the extra speed, map is slightly faster:

    >>> d = lambda a, b: map(list, zip(a, b))
    >>> d(a, b)
    [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
    

    However, map is considered unpythonic and should only be used for performance tuning.

    0 讨论(0)
  • 2020-12-07 13:46

    If you are zipping more than 2 lists (or even only 2, for that matter), a readable way would be:

    [list(a) for a in zip([1,2,3], [4,5,6], [7,8,9])]
    

    This uses list comprehensions and converts each element in the list (tuples) into lists.

    0 讨论(0)
  • 2020-12-07 13:46

    How about this?

    >>> def list_(*args): return list(args)
    
    >>> map(list_, range(5), range(9,4,-1))
    [[0, 9], [1, 8], [2, 7], [3, 6], [4, 5]]
    

    Or even better:

    >>> def zip_(*args): return map(list_, *args)
    >>> zip_(range(5), range(9,4,-1))
    [[0, 9], [1, 8], [2, 7], [3, 6], [4, 5]]
    
    0 讨论(0)
  • 2020-12-07 13:49

    List comprehension would be very simple solution I guess.

    a=[1,2,3,4,5,6]
    
    b=[7,8,9,10,11,12]
    
    x = [[i, j] for i, j in zip(a,b)]
    
    print(x)
    
    output : [[1, 7], [2, 8], [3, 9], [4, 10], [5, 11], [6, 12]]
    
    0 讨论(0)
  • 2020-12-07 13:54

    Using numpy

    The definition of elegance can be quite questionable but if you are working with numpy the creation of an array and its conversion to list (if needed...) could be very practical even though not so efficient compared using the map function or the list comprehension.

    import numpy as np 
    a = b = range(10)
    zipped = zip(a,b)
    result = np.array(zipped).tolist()
    Out: [[0, 0],
     [1, 1],
     [2, 2],
     [3, 3],
     [4, 4],
     [5, 5],
     [6, 6],
     [7, 7],
     [8, 8],
     [9, 9]]
    

    Otherwise skipping the zip function you can use directly np.dstack:

    np.dstack((a,b))[0].tolist()
    
    0 讨论(0)
提交回复
热议问题