我有一個嵌套的坐標串列[[x1, y1],[x2, y2],[x3,y3]...]。
我想使用 afor-loop來確定兩個連續點之間在 x 方向上的距離。我想稍后對 y 方向做同樣的事情。到目前為止,這是我的嘗試:
p1=[X1, Y1]
p2=[X2, Y2]
p3=[X3, Y3]
p4=[X4, Y4]
p5=[X5, Y5]
coordiantes = [p1, p2, p3, p4, p5]
for i in coordinates:
p1_x = i[0]
p2_x = i[0] 1
p1_y = i[1]
p2_y = i[1] 1
distance_x = p2_x - p1_x
顯然,i[0] 1不會為您提供下一個串列中的后續 x 值,而是添加1到第一個 x 值。
我的問題是如何參考嵌套串列中的后續 x 值?所以,如果i提到p1,我也想進入p2那個回圈。
我還嘗試添加另一個變數j并分配它,j = i 1以便我可以使用 j[0] 來參考后續的 x 值。但是,我收到了無法將串列連接到 int 的錯誤。
先感謝您!
uj5u.com熱心網友回復:
for i in coordinates是一個 for-each 回圈。您無權訪問當前索引,i直接是串列子項。
如果您想通過增加當前索引來訪問相鄰專案,您應該回圈使用range或enumerate。例如,
for ind in range(len(coordinates)-1):
p1_x = coordinates[ind][0]
p2_x = coordinates[ind 1][0]
p1_y = coordinates[ind][1]
p2_y = coordinates[ind 1][1]
distance_x = p2_x - p1_x
范圍限制是 len-1,因為我們不想處理最后一個元素(ind 1 將超出范圍)。
uj5u.com熱心網友回復:
for i, n in enumerate(coord):
try:
print(coord[i]
print(coord[i 1])
except IndexError:
pass
嘗試/除了 indexerror 的部分。除此之外,最后一位數字出現錯誤。或者你也可以使用:
for i, n in enumerate(coord):
if i == len(coord)-1:
pass
else:
print(coord[i])
print(coord[i 1])
另外,對于 enumerate 基本上你可以使用range(len(coord))并且不使用try/except 和 if partrange(len(coord)-1)給出你想要的
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/394353.html
