Saya memiliki daftar koordinat dan daftar nilai ketinggian lainnya. Bagaimana saya bisa menambahkan nilai ketinggian ke daftar koordinat secara berurutan?

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]

Hasil yang diharapkan:

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]]
0
jinha kim 16 Januari 2020, 04:20

2 jawaban

Jawaban Terbaik

Tldr: Solusi satu baris, zip iterables (Python docs) dan daftar untuk penjelasan output yang diinginkan di bawah ini:

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

Penjelasan:

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

Keluaran:

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]

Sebagai pemahaman daftar satu baris:

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

Keluaran:

[[[['a', 'a'], ['aa', 'aa']], 1], [[['b', 'b'], ['bb', 'bb']], 2]]
-1
pajamas 10 September 2020, 08:56

Jika Anda tidak keberatan dengan tupel, Anda bisa menggunakan zip

> list(zip(coor, height))

[([[83.75, 18.7], [57.5, 18.7], [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),
 ...

Jika harus berupa daftar, gunakan zip dalam pemahaman.

> [list(pair) for pair in zip(coor, height)]

[[[83.75, 18.7], [57.5, 18.7], [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],
...
2
Mark M 16 Januari 2020, 01:27