-1

I have a combined list of lat, lon and alt in a sequence as shown below, now I want to divide the list into 3 parts 1st for lat, 2nd for lon and third for alt.

coords = [48.92504247289378, 9.147973368734435, 29707, 48.92504291087322, 9.147998449546572, 29707, 48.9250463088055, 9.148013780873235, 29707, 48.92505484289239, 9.148021595289876, 29707, 48.925070689333246, 9.148024125370592, 29707]

#list format = [lat,lon,alt,lat,lon,alt.....]

excepted output:

lat = [48.92504247289378,48.92504291087322,48.9250463088055....]
lon = [9.147973368734435,9.147998449546572, 9.148013780873235...]
alt = [29707,29707,29707,...]

I tried:

Split a python list into other "sublists" i.e smaller lists

Python: Split a list into sub-lists based on index ranges

Split a list into parts based on a set of indexes in Python

And a few other solutions, but none of them worked.

Can anyone help me to get the expected output?

Asocia
  • 5,935
  • 2
  • 21
  • 46
L Lawliet
  • 419
  • 1
  • 7
  • 20

3 Answers3

2

How about:

l = [48.92504247289378, 9.147973368734435, 29707, 48.92504291087322, 9.147998449546572, 29707, 48.9250463088055, 9.148013780873235, 29707, 48.92505484289239, 9.148021595289876, 29707, 48.925070689333246, 9.148024125370592, 29707]
res = [[*l[i::3]] for i in range(3)]

The outputs are:

>>> res[0]
[48.92504247289378, 48.92504291087322, 48.9250463088055, 48.92505484289239, 48.925070689333246]
>>> res[1]
[9.147973368734435, 9.147998449546572, 9.148013780873235, 9.148021595289876, 9.148024125370592]
>>> res[2]
[29707, 29707, 29707, 29707, 29707]

Another possible solution using numpy is:

import numpy as np
l_np = np.array(l)
n = 3
res = l_np.reshape(int(l_np.shape[0]/n), n).T

print(res)

array([[4.89250425e+01, 4.89250429e+01, 4.89250463e+01, 4.89250548e+01,
        4.89250707e+01],
       [9.14797337e+00, 9.14799845e+00, 9.14801378e+00, 9.14802160e+00,
        9.14802413e+00],
       [2.97070000e+04, 2.97070000e+04, 2.97070000e+04, 2.97070000e+04,
        2.97070000e+04]])

Where each row in the res matrix is the desired result.

David
  • 8,113
  • 2
  • 17
  • 36
2

Just slicing the list would work:

coords = [48.92504247289378, 9.147973368734435, 29707, 48.92504291087322, 9.147998449546572, 29707, 48.9250463088055, 9.148013780873235, 29707, 48.92505484289239, 9.148021595289876, 29707, 48.925070689333246, 9.148024125370592, 29707]
lat = coords[::3]
lon = coords[1::3]
alt = coords[2::3]
Asocia
  • 5,935
  • 2
  • 21
  • 46
1
lat = []
lon = []
alt = []

for i in range(len(coords)):
   if i % 3 == 0:
      lat.append(coords[i])
   elif i % 3 == 1:
      lon.append(coords[i])
   else:
      alt.append(coords[i])
A Bear
  • 59
  • 6