Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write coordinates of array of values in multidimensional array

I have this list:

list = [[0, 5], [0, 3, 6], [1, 2, 4], [1, 7], [0, 1]]

Each element refers to a point with coordinates listed as two arrays:

Lon = [2.0,3.0,5.0,2.0,6.0,1.0,3.0,4.0]
Lat = [4.0,6.0,5.0,3.0,4.0,2.0,1.0,7.0]

I am trying to create an array that is in the following format:

[[Lon_0,Lat_0],[Lon_5,Lat_5]]
[[Lon_0,Lat_0],[Lon_3,Lat_3],[Lon_6,Lat_6]]
...

I tried the zip function but something is missing and I don't know how to move forward:

for m in list:
    for n in m:
        Coord = zip((Lon[n], Lat[n]))

Any help is appreciated

like image 466
mb567 Avatar asked Feb 02 '26 23:02

mb567


1 Answers

You can go through each index inside each element of your list and rebuild an entry with the Lon, Lat values.

Here is the code:

# Sample data
list = [[0, 5], [0, 3, 6], [1, 2, 4], [1, 7], [0, 1]]
Lon = [2.0,3.0,5.0,2.0,6.0,1.0,3.0,4.0]
Lat = [4.0,6.0,5.0,3.0,4.0,2.0,1.0,7.0]

# Construct result list
result = []                                                                                                                          
for entry in list:
    elem = []
    for index in entry:
        elem.append([Lon[index], Lat[index]])
    result.append(elem)

# Sample output
print(result)
[[[2.0, 4.0], [1.0, 2.0]], 
 [[2.0, 4.0], [2.0, 3.0], [3.0, 1.0]], 
 [[3.0, 6.0], [5.0, 5.0], [6.0, 4.0]], 
 [[3.0, 6.0], [4.0, 7.0]], 
 [[2.0, 4.0], [3.0, 6.0]]]

In a more "pythonic" way you can use a single-line command (which might be harder to understand but does the exact same thing):

result = [[[Lon[index], Lat[index]] for index in entry] for entry in list]
like image 76
Cristian Ramon-Cortes Avatar answered Feb 04 '26 12:02

Cristian Ramon-Cortes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!