2 回答
TA贡献1865条经验 获得超7个赞
您可以将以下代码包装在一个函数中并使用它:
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]
结果符合您的预期。
TA贡献1871条经验 获得超8个赞
以下是我解决问题的方法。我认为之前的答案使用的正则表达式可能会慢一点(需要进行基准测试)。
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]
添加回答
举报