使用for循环遍历列表时出现IndexError [英] IndexError when iterating over lists using for loops

查看:69
本文介绍了使用for循环遍历列表时出现IndexError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I keep getting an IndexError(list index out of range) when iterating over x and y in the for loop even though the length of x and y are equal. What could I be doing wrong?

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)

推荐答案

i j 是列表的元素,而不是索引,因此没有任何意义使用 x [i] .

i and j are elements of the lists, not indexes, so it doesn't make sense to use x[i].

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

Don't put the coordinates in separate lists, use a single list with tuples.

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

Other issues: You need to append to distance, not overwrite it each time through the loop. You need to calculate perimiter at the end; you're calculating it when the perimimter list is empty.

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

You don't need to use abs(), since you're squaring it, and the square of a negative number is the same as the corresponding positive number.

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

Instead of checking the index and using break to stop before you reach the last index, use a slice to iterate one less time.

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)

这篇关于使用for循环遍历列表时出现IndexError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆