简体   繁体   中英

How to separate string coordinates into 2 lists: Latitude and Longitude

Currently, I have a list of string tuple coordinates: latitude and longitude. I want to split this list of tuple coordinates into a latitude list and longitude list. How should I go about achieving that? I tried using the zip function and that isn't working. My current code is below.

latlon_ = [x[0] for x in latlon]
latlon_

This returns:

['(39.36356356, -76.53434457)',
 '(39.27426334, -76.54542274)',
 '(39.36461879, -76.56234642)',
 '(39.26932875, -76.60509948)',
 '(39.30447891, -76.61359834)',
 '(39.30411637, -76.61357519)',
 '(39.33636159, -76.6802207)',]

And, I would like to have 2 lists: longitude and latitude.

I would first apply regex like this:

import re
pattern = re.compile("\d+[.]\d+")
latlon_ = [re.findall(pattern, tpl) for tpl in latlon_]

Then you have latlon_ in a format you can work with and apply two more list comprehensions to extract longitude and latitude as floats:

long = [float(tpl[0]) for tpl in latlon_]
lat = [float(tpl[1]) for tpl in latlon_]
latlon = [('(39.36356356, -76.53434457)',), ('(39.27426334, -76.54542274)',), ('(39.36461879, -76.56234642)',), ]
lat,lon = list(zip(*[eval(x[0]) for x in latlon]))
print(f'lat = {list(lat)}\nlon = {list(lon)}')

Prints:

lat = [39.36356356, 39.27426334, 39.36461879]
lon = [-76.53434457, -76.54542274, -76.56234642]
source_list=['(39.36356356, -76.53434457)',
 '(39.27426334, -76.54542274)',
 '(39.36461879, -76.56234642)',
 '(39.26932875, -76.60509948)',
 '(39.30447891, -76.61359834)',
 '(39.30411637, -76.61357519)',
 '(39.33636159, -76.6802207)',]

latitude=[x.split(',')[0][1:] for x in source_list]
longitude=[x.split(',')[1][2:].replace(')','') for x in source_list]

print('latitude: ', latitude)
print('longitude:', longitude)

Output:

latitude:  ['39.36356356', '39.27426334', '39.36461879', '39.26932875', '39.30447891', '39.30411637', '39.33636159']
longitude: ['76.53434457', '76.54542274', '76.56234642', '76.60509948', '76.61359834', '76.61357519', '76.6802207']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM