Search code examples
pythonappendsequential

How can I append two lists in sequential order in python?


I have a list of coordinates and another list of height values. How can I append height values to coordinate list in sequential order?

coor = [[[83.75, 18.70], [57.50, 18.70], [57.5, 2.87], [83.75, 4.18]],
   [[83.75, 34.54], [110.0, 35.0], [104.86, 19.59], [83.75, 19.59]],
   [[104.86, 19.59], [83.75, 19.59], [83.75, 4.18], [100.0, 5.0]],
   [[-5.0, 33.0], [18.12, 33.40],[18.12, 16.70],[-2.53, 16.70]], 
   [[18.12, 16.70],[-2.53, 16.70], [0.0, 0.0],[18.12, 0.90]]]
height = [5,4,5,6,6]

expected result:

result = [[[83.75, 18.70], [57.50, 18.70], [57.5, 2.87], [83.75, 4.18],5],
   [[83.75, 34.54], [110.0, 35.0], [104.86, 19.59], [83.75, 19.59],4],
   [[104.86, 19.59], [83.75, 19.59], [83.75, 4.18], [100.0, 5.0],5],
   [[-5.0, 33.0], [18.12, 33.40],[18.12, 16.70],[-2.53, 16.70],6], 
   [[18.12, 16.70],[-2.53, 16.70], [0.0, 0.0],[18.12, 0.90],6]]

Solution

  • tldr: One line solution, zip the iterables (Python docs) and list for desired output explanation below:

    [list(item) for item in list(zip(coor,height))]
    

    explanation:

    list1 = [ 
        [['a','a'],['aa','aa']], 
         [['b','b'],['bb','bb']]]
    list2 = [1,2]
    
    for item in list(zip(list1,list2)): 
        print('zip output', item) 
        print('desired output', list(item)) 
    

    Output:

    zip output ([['a', 'a'], ['aa', 'aa']], 1)
    desired output [[['a', 'a'], ['aa', 'aa']], 1]
    zip output ([['b', 'b'], ['bb', 'bb']], 2)
    desired output [[['b', 'b'], ['bb', 'bb']], 2]
    

    as one line list comprehension :

    [list(item) for item in list(zip(list1,list2))]
    

    Output:

    [[[['a', 'a'], ['aa', 'aa']], 1], [[['b', 'b'], ['bb', 'bb']], 2]]