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]
添加回答
舉報