0

我有一个运行 16 次的循环,因为它读取的文件中有 16 行,我正在使用一个循环来读取时间戳的前两个字符。但我不知道如何防止 n 变量达到 17。我尝试使用 while 条件将 n 限制为 16,但无济于事。这是我的全部功能,我正在尝试为飓风艾琳的路径制作动画,详见http://calicoproject.org/Calico_Python_GIS

def drawIrene(win):
line = Line()
n = 0
for (x,y) in dots:
    time_stamp[n] = time_stamp[n][:2]
    time_stamp[n+1] = time_stamp[n+1][:2]
    time1 = abs(int(time_stamp[n]) - 12)
    time2 = abs(int(time_stamp[n+1]) - 12)
    wait_time = abs(int(time1) - int(time2))
    x, y = ll2xy(x, y)
    c = Circle(Point(x, y), int(eye_size[n]))
    line.append(Point(x,y))
    c.fill = Color(255, 255, 0, 62)
    c.draw(win)
    t = Polygon((x, y), (x+10, y+5), (x+int(movement_speed[n]), y-int(movement_speed[n])/2))
    t.fill = Color("orange")
    t.draw(win)
    print(time1)
    print(time2)
    print()
    #print (wait_time)
    wait(wait_time)
    if n < len(dots):
        n += 1
    else:
        break
line.draw(win)
line.border = 2
4

1 回答 1

1

问题是您正在循环两个相同长度的序列,dots并且time_stamp. 但是,您在序列中向前看time_stamp,访问当前项目和下一个项目以计算wait_time值。这导致您IndexError最后一次通过循环,因为n+1索引指向列表末尾。

有几种不同的方法可以解决此问题。你可以修改你的数据结构,要么dots少一个元素,要么time_stamp多一个。或者你可以简单地少循环一次,如评论中所建议的那样。

但我认为最好的解决方案是更改循环中的逻辑,以便wait_time在第一个或最后一个循环中进行不同的计算。例如,您可以选择在最后一个周期没有延迟。

这是一些可以做到这一点的代码。它是最后一次通过的特殊情况,其中n等于len(time_stamp)-1,并且在这种情况下简单地设置wait_time为零。请注意,我是n从循环中的内置enumerate函数生成的for,因此不需要将其初始化为零或手动更新:

for n, (x, y) in enumerate(dots):
    if n < len(time_stamp)-1:
        time_stamp[n] = time_stamp[n][:2]
        time_stamp[n+1] = time_stamp[n+1][:2]
        time1 = abs(int(time_stamp[n]) - 12)
        time2 = abs(int(time_stamp[n+1]) - 12)
        wait_time = abs(int(time1) - int(time2))
    else: # special case n >= len(time_stamp)-1, which should be the last pass
        wait_time = 0
    x, y = ll2xy(x, y)
    c = Circle(Point(x, y), int(eye_size[n]))
    line.append(Point(x,y))
    c.fill = Color(255, 255, 0, 62)
    c.draw(win)
    t = Polygon((x, y), (x+10, y+5),
                (x+int(movement_speed[n]), y-int(movement_speed[n])/2))
    t.fill = Color("orange")
    t.draw(win)
    wait(wait_time)
于 2012-12-25T00:58:45.997 回答