【问题标题】:IndexError when iterating over lists using for loops使用 for 循环遍历列表时出现 IndexError
【发布时间】:2020-05-22 22:31:37
【问题描述】:

在 for 循环中迭代 x 和 y 时,即使 x 和 y 的长度相等,我也会不断收到 IndexError(list index out of range)。我可能做错了什么?

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)

【问题讨论】:

  • 它在第二个 for 循环中。这里 i 和 j 实际上是 x 和 y 内部的值,而不是索引。只是这样做: for i in range(len(x)): 代替它应该可以工作。

标签: python list


【解决方案1】:

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

不要将坐标放在单独的列表中,使用带有元组的单个列表。

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

您不需要使用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)

【讨论】:

    猜你喜欢
    • 2019-09-07
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多