I am working on a Django platform where i am supposed to submit a list of polygon coordinates from google maps to search through a dataset. So far, i have managed to collect the coordinates from the frontend but they are mixed up i.e the longitudes start then latitude follows and ideally ,the longitudes are supposed to start then the latitudes to follow
Here is a working sample of the list i have:
coordinates = [65.56147597726766, -104.83033675930798, 64.44751706485646, -93.93189925930798, 58.232434372977615, -98.85377425930798]
The desired format should be:
coordinates = [-104.83033675930798,65.56147597726766, -93.93189925930798,64.44751706485646, -98.85377425930798,58.232434372977615]
Any help will be highly appreciated.
CodePudding user response:
You can work with list comprehension where we use slices of the original list:
[x for i in range(0, len(coordinates), 2) for x in reversed(coordinates[i:i 2])]
for the given sample data, we get:
>>> coordinates = [65.56147597726766, -104.83033675930798, 64.44751706485646, -93.93189925930798, 58.232434372977615, -98.85377425930798]
>>> [x for i in range(0, len(coordinates), 2) for x in reversed(coordinates[i:i 2])]
[-104.83033675930798, 65.56147597726766, -93.93189925930798, 64.44751706485646, -98.85377425930798, 58.232434372977615]
CodePudding user response:
You could do:
coordinates = [65.56147597726766, -104.83033675930798, 64.44751706485646, -93.93189925930798, 58.232434372977615, -98.85377425930798]
res = [val for coo in zip(coordinates[1::2], coordinates[::2]) for val in coo]
print(res)
Output
[-104.83033675930798, 65.56147597726766, -93.93189925930798, 64.44751706485646, -98.85377425930798, 58.232434372977615]
CodePudding user response:
Another way:
coordinates = [65.56147597726766, -104.83033675930798, 64.44751706485646, -93.93189925930798, 58.232434372977615, -98.85377425930798]
result = coordinates[1:] [0]
result[1::2] = coordinates[0::2]