Python错误:列表赋值索引超出范围

-1 投票
3 回答
3131 浏览
提问于 2025-04-16 20:17

我正在尝试初始化一个列表,但总是出现索引超出范围的错误:

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

这段代码是用来处理一些特定的任务的。它可能涉及到一些数据的操作,或者是与用户的输入进行交互。具体来说,代码块中的内容会根据不同的情况执行不同的功能。

在编程中,我们常常会用到类似的代码结构来让程序更灵活,能够根据不同的条件做出不同的反应。这样一来,程序就能更好地满足用户的需求。

如果你对这段代码有疑问,可以尝试逐行分析,看看每一行的作用是什么,慢慢就能理解它的整体功能了。

self.nodes = [[[]] * self.columns] * self.rows
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

什么是 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], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]

撰写回答