使用for循环遍历列表时出现IndexError

时间:2020-05-22 22:31:37

标签: python list

即使在x和y的长度相等的情况下,在for循环中对x和y进行迭代时,我仍然得到IndexError(列表索引超出范围)。我可能做错了什么?

from math import sqrt
x = []
y = []
distance = []
perimeter = sum(distance)

while True:
   x.append(int(input('Enter x value of a point: ')))
   y.append(int(input('Enter y value of the point: ')))
   if x[-1] == 0 and y[-1] == 0:
      break

for i,j in zip(x, y):
   distance = sqrt((abs((x[i]) - (x[i+1])))**2 + (abs((y[i]) - (y[i+1])))**2)
   if i == len(x):
      break

print(perimeter)

1 个答案:

答案 0 :(得分:0)

ij是列表的元素,而不是索引,因此使用x[i]没有意义。

不要将坐标放在单独的列表中,而是将单个列表与元组一起使用。

其他问题:您需要附加到distance,而不是每次循环都覆盖它。您需要最后计算perimiterperimimter列表为空时,您正在计算它。

您不需要使用abs(),因为您要对它进行平方,并且负数的平方与对应的正数相同。

与其检查索引并使用break在到达最后一个索引之前停止,不如使用切片减少一个迭代时间。

from math import sqrt
coords = []
distance = []

while True:
    xvalue = int(input('Enter x value of the point: '))
    if xvalue == 0:
        break
    yvalue = int(input('Enter y value of the point: '))
    coords.append((x, y))

for i, (x, y) in coords[:-1]:
    nextx, nexty = coords[i+1]
    distance.append(sqrt((x - nextx)**2 + (y - nexty)**2))

perimiter = sum(distance)