简体   繁体   中英

Python, convert coordinate degrees to decimal points

I have a list of latitude and longitude as follows:

['33.0595° N', '101.0528° W']

I need to convert it to floats [33.0595, -101.0528] .

Sure, the '-' is the only difference, but it changes when changing hemispheres, which is why a library would be ideal, but I can't find one.

You can wrap the following code in a function and use it:

import re

l = ['33.0595° N', '101.0528° W']
new_l = []
for e in l:
    num = re.findall("\d+\.\d+", e)
    if e[-1] in ["W", "S"]:
        new_l.append(-1. * float(num[0]))
    else:
        new_l.append(float(num[0]))

print(new_l)  # [33.0595, -101.0528]

The result match what you expect.

The following is the way I would solve the issue. I think the previous answer uses regex that might prove to be a bit slower (would need benchmarking).

data = ["33.0595° N", "101.0528° W"]


def convert(coord):
    val, direction = coord.split(" ") # split the direction and the value
    val = float(val[:-1]) # turn the value (without the degree symbol) into float
    return val if direction not in ["W", "S"] else -1 * val # return val if the direction is not West


converted = [convert(coord) for coord in data] # [33.0595, -101.0528]

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