为了账号安全,请及时绑定邮箱和手机立即绑定

如果在不同时间运行程序后出现 IndexError 但出现在不同位置,这意味着什么?

如果在不同时间运行程序后出现 IndexError 但出现在不同位置,这意味着什么?

眼眸繁星 2022-11-18 20:56:13
我正在尝试为我自己的自我发展项目创建 John Conway 的人生游戏。我遇到的一般问题是让动画在 GUI 上可视化,现在我收到的错误消息如下:Exception in Tkinter callbackTraceback (most recent call last):  File "D:\Software\Python\lib\tkinter\__init__.py", line 1705, in __call__    return self.func(*args)  File "gameoflife.py", line 70, in one_cycle    apply_rules()  File "gameoflife.py", line 56, in apply_rules    updated_grid[row][column] = 0IndexError: list index out of range但是如果我第二次运行它,我会在它最初说错误的下面的不同行上得到同样的错误。我知道实际的错误是告诉我我试图访问的索引不在列表中,但我不明白为什么它会出现在下面的行中,就好像上一行已被更正一样。我的代码如下:from tkinter import *from random import *import timeimport numpy as npPIXEL_SIZE = 10ROW = 910COLUMN = 700grid = []updated_grid = [[]]def create_grid():    for row in range(0, ROW):        grid2 = []        for column in range(0, COLUMN):            grid2.append(randint(0, 1))        grid.append(grid2)def draw_grid():    for row in range(0, ROW):        for column in range(0, COLUMN):            if grid[row][column] == 1:                x0 = row*PIXEL_SIZE                y0 = column*PIXEL_SIZE                x1 = x0+PIXEL_SIZE                y1 = y0+PIXEL_SIZE                canvas.create_rectangle(x0, y0, x1, y1, fill='red')def apply_rules():    for row in range(1, ROW - 1):        for column in range(1, COLUMN - 1):            neighbours_count = 0            # will count the neighbours for each cell            neighbours_count += grid[row-1][column-1] # top left            neighbours_count += grid[row][column-1] # top center            neighbours_count += grid[row+1][column-1] # top right            neighbours_count += grid[row-1][column] # middle left            neighbours_count += grid[row+1][column] # middle right            neighbours_count += grid[row-1][column+1] # bottom left            neighbours_count += grid[row][column+1] # bottom center            neighbours_count += grid[row+1][column+1] # bottom right
查看完整描述

2 回答

?
MMTTMM

TA贡献1869条经验 获得超4个赞

你从未填写过updated_grid,所以你不能分配给它的元素。


您应该在程序启动时创建两个网格。


def create_grid(ROW, COLUMN):

    grid = []

    for row in range(0, ROW):

        grid2 = []

        for column in range(0, COLUMN):

            grid2.append(randint(0, 1))

        grid.append(grid2)

    return grid


grid = create_grid(ROW, COLUMN)

updated_grid = create_grid(ROW, COLUMN)


查看完整回答
反对 回复 2022-11-18
?
POPMUISE

TA贡献1765条经验 获得超5个赞

最简单的解决方案是复制现有的网格并在以后使用该网格:


import copy


def apply_rules():

    global grid

    updated_grid = copy.deepcopy(grid)

    # the rest of the function here, except the copying back again


    # This is all that's needed to 'copy' it back again:

    grid = updated_grid

这样,您从网格的副本开始:( copy.deepcopy(grid)) 并像您一样覆盖元素:( 例如updated_grid[row][column] = 0) 最后处理旧网格并将新网格保持在一行中:( grid = updated_grid) 通过引用计数的魔力.


这是一种形式double buffering。


查看完整回答
反对 回复 2022-11-18
  • 2 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信