Python错误:列表分配索引超出范围

时间:2011-06-25 22:29:24

标签: python list

我正在尝试初始化列表并继续使索引超出范围:

self.nodes = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]

当我运行此代码时:

for i in range(self.rows):
            for j in range(self.columns):
                if self.GRID[i][j] == 0:
                    self.walkable.append(Node(j * self.cellSize, i * self.cellSize))
                    self.isWalkable = True
                if self.GRID[i][j] == 1:
                    self.unwalkable.append(Node(j * self.cellSize, i * self.cellSize))
                    self.isWalkable = False
                if self.GRID[i][j] == 2:
                    self.player = Node(j * self.cellSize, i * self.cellSize)
                    self.isWalkable = True
                if self.GRID[i][j] == 3:
                    self.npc = Node(j * self.cellSize, i * self.cellSize)
                    self.isWalkable = True

                self.nodes[i][j] = Node(j, i)
                self.nodes[i][j].setWalkable(self.isWalkable)

我得到的错误是:

self.nodes[i][j] = Node(j, i)
IndexError: list assignment index out of range

3 个答案:

答案 0 :(得分:2)

分配给列表中不存在的索引失败。在您的情况下,您尝试分配空列表的索引j

self.nodes = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
# assume i == 0 and j == 0
self.nodes[i] # refers to the first empty list []
self.nodes[i][j] ## does not exist

考虑将self.nodes[i][j] = Node(j, i)替换为self.nodes[i].append(Node(j, i))

或者,确保使用嵌套列表初始化self.nodes,如@yi_H所述

编辑确定,而不是完全,如yi_H所述。如果要创建表示表的二维数组,可以使用

执行此操作
self.nodes = [ [None for col in range(self.cols) ] for row in range(self.rows)]

答案 1 :(得分:1)

什么是Node()

>>> nodes = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
>>> nodes[0][0] = 5
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
IndexError: list assignment index out of range
>>> nodes[0].append(5)
>>> nodes
[[5], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]

答案 2 :(得分:0)

self.nodes = [[[]] * self.columns] * self.rows