问题描述
我有以下经纬度列表:
['33.0595° N','101.0528° W']
我需要将其转换为浮点数[33.0595,-101.0528]
。
当然,“-”是唯一的区别,但是当改变半球时它会改变,这就是为什么图书馆是理想的,但我找不到图书馆的原因。
解决方法
您可以将以下代码包装在一个函数中并使用它:
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]
结果符合您的期望。
,以下是我解决问题的方法。我认为以前的答案使用的正则表达式可能会变慢(需要进行基准测试)。
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]