我想從2個列表中取出距離txt文件的座標,我找不出它出了什麼問題,因爲它不會刪除每個座標如果距離大於12米,則不通過if語句,刪除列表中的項目。Python - 循環 - 距離計算列表刪除
代碼:
x = [] # contains a list of x coordinates in EPGS: 2202
y = [] # contains a list of y coordinates in EPGS: 2202
keepItWorking = 0 # this is supposed to avoid offset once a coordinate is deleted.
xStore = x[0] # Stores x variable to evaluate distance and delete coordinates.
yStore = y[0] # Stores y variable to evaluate distance and delete coordinates.
def distance(x1, x2, y1, y2):
return (math.sqrt(((x2 - x1)**2) + ((y2 - y1)**2)))
for i in range(1, len(x)):
try:
if distance(x[i - keepItWorking], xStore, y[i - keepItWorking], yStore) > 12 #if distance is greater than 12 store coordinates values and proceed to delete next coordinates with the new evaluation.
xStore = x[i - keepItWorking]
yStore = y[i - keepItWorking]
elif distance(x[i - keepItWorking], xStore, y[i - keepItWorking], yStore) < 12 # if distance is lower than 12 meters delete values from list.
del x[i - keepItWorking]
del y[i - keepItWorking]
keepItWorking = keepItWorking + 1
except IndexError: # avoids error when index gets out of range becouse of the items eliminations.
continue
顯然我固定的,而在這裏重寫代碼,我遇到的問題...這是可以正常使用。
請您與我們分享一些數據? –
按索引迭代時從列表中刪除元素是有問題的。當你刪除一個元素時,所有的索引都會移動1. –
x [0]是否總是對應於y [0]?爲什麼不把座標存儲爲一個列表有序對(元組)? Code-Apprentice是對的。我認爲使用列表理解是最好的選擇。你能分享一個點的樣本列表,需要進行哪些比較,以及你期望過濾的列表看起來像什麼? – RagingRoosevelt