Zip with list output instead of tuple

前端 未结 7 2036
梦毁少年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: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()
    

提交回复
热议问题