列表索引超出范围

时间:2012-10-03 03:19:28

标签: python list

如何修复此错误,pos_coordinates包含值列表,updatePos_coordinates是先前pos_coordiantes值复制到updatePos_coordinates列表中。我想找到对象和索引值8,9,12和13之间的差异,但我一直在收到此错误。我该如何解决这个问题

    screen_width = 0
    screen_height = 0
    updatePos_coordinates = []

    while True:
        client_socket.send("loc\n")
        data = client_socket.recv(8192)
        pos_coordinates = data.split()

        if(not(pos_coordinates[-1] == "eom" and pos_coordinates[0] == "start")):
            continue

        if (screen_width != int(pos_coordinates[2])):
            screen_width = int(pos_coordinates[2])
            screen_height = int(pos_coordinates[3])

        if (pos_coordinates != updatePos_coordinates):
            if(cmp(pos_coordinates[8:10], updatePos_coordinates[8:10]) == 0):
                both.brake()
                print "Ball is in the same location.."
            if((pos_coordinates[8] - updatePos_coordinates[8] > 5) or (pos_coordinates[8] - updatePos_coordinates[8] < -5) or (pos_coordinates[9] - updatePos_coordinates[9] > 5) or (pos_coordinates[9] - updatePos_coordinates[9] < -5)):     
                activateRobot(pos_coordinates)
            else:
                both.brake()
                print "Ball is in the same location.."

        updatePos_coordinates = pos_coordinates[:]
        time.sleep(3)
        print '...........'

我继续这样做:

Traceback (most recent call last):
  File "test.py", line 155, in <module>
    if((pos_coordinates[8] - updatePos_coordinates[8] > 5) or (pos_coordinates[8] - updatePos_coordinates[8] < -5) or (pos_coordinates[9] - updatePos_coordinates[9] > 5) or (pos_coordinates[9] - updatePos_coordinates[9] < -5)):     
IndexError: list index out of range

1 个答案:

答案 0 :(得分:0)

当您还没有任何元素时,您正试图访问updatePos_coordinates[8],因为自您将其定义为updatePos_coordinates = []后它尚未更改。

您应该在循环之前使用默认值填充updatePos_coordinates

例如:

updatePos_coordinates = ['' for _ in range(16)]
# replace 16 with length of pos_coordinates

或者,您可以在第一次循环时使两个坐标彼此相等。

if len(updatePos_coordinates) < 16:
    updatePos_coordinates = pos_coordinates[:]

elif pos_coordinates != updatePos_coordinates:
    ...

我还注意到,当它们实际上是字符串时,你正在将坐标视为整数。