猿问

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

我正在尝试为我自己的自我发展项目创建 John Conway 的人生游戏。我遇到的一般问题是让动画在 GUI 上可视化,现在我收到的错误消息如下:


Exception in Tkinter callback

Traceback (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] = 0

IndexError: list index out of range

但是如果我第二次运行它,我会在它最初说错误的下面的不同行上得到同样的错误。我知道实际的错误是告诉我我试图访问的索引不在列表中,但我不明白为什么它会出现在下面的行中,就好像上一行已被更正一样。我的代码如下:


from tkinter import *

from random import *

import time

import numpy as np


PIXEL_SIZE = 10

ROW = 910

COLUMN = 700

grid = []

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

眼眸繁星
浏览 133回答 2
2回答

MMTTMM

你从未填写过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 gridgrid = create_grid(ROW, COLUMN)updated_grid = create_grid(ROW, COLUMN)

POPMUISE

最简单的解决方案是复制现有的网格并在以后使用该网格:import copydef 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。
随时随地看视频慕课网APP

相关分类

Python
我要回答