[英]Python - How can i remove a letter from a list of strings, change the strings to floats, transform some of the floats, and keep the order
myList=['57.43 N', '44.78 S', '59.64 S', '88.11 N']
我正在學習python,我有一個表示Lat/Lon
的字符串列表。 我需要刪除N/S
並且在S
乘以-1
時將所有字符串都轉換為floats
。 我當時以為我可以建立我的值的索引,然后以某種方式將帶有S的字符串與帶有N的字符串分開,創建北列表和南列表以刪除N / S,
x=[x.remove('NS') for x in myList]
y=[y.remove('S') for x in myList]
將y列表乘以-1,並使用x擴展y,以便我的索引保持原樣。 任何建議將是非常可愛的。 謝謝。
您可以使用列表推導簡潔地實現此目的:
newList = [-1 * float(x[:-2]) if 'S' in x else float(x[:-2]) for x in mylist]
當然,這假設您的每個元素都具有以下特征:
' N'
或' S'
。 您可以將每個字符串分成數字和方向。 如果方向為S
,則將其乘以-1
:
myList=['57.43 N', '44.78 S', '59.64 S', '88.11 N']
result = []
for data in myList:
num, direction = data.split()
num = float(num)
if direction == 'S':
num *= -1
result.append(num)
print(result)
# [57.43, -44.78, -59.64, 88.11]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.