Python的列表索引必须是整数,而不是元组"错误

Lib*_*ban 3 python arrays grid robot list

我正在努力将机器人移动到8 x 8的2d网格室,其中一部分是初始化传感器,其中包括机器人周围最近的5个瓦片.

self.sensors = [0 for x in xrange(5)]
Run Code Online (Sandbox Code Playgroud)

在这里,我正在创建一个由5个元素组成的空数组.

但是当我尝试像这样设置传感器的值时:

    if self.heading == 'East':
        self.sensors[0] = self.room[self.x, self.y-1]
        self.sensors[1] = self.room[self.x+1, self.y-1]
        self.sensors[2] = self.room[self.x+1, self.y]
        self.sensors[3] = self.room[self.x+1, self.y+1]
        self.sensors[4] = self.room[self.x, self.y+1]
Run Code Online (Sandbox Code Playgroud)

我得到'列表索引必须是整数而不是元组'的错误.

Sve*_*ach 7

你说self.room是一个"2d网格" - 我假设它是一个列表列表.在这种情况下,您应该访问其元素

self.room[self.x][self.y-1]
Run Code Online (Sandbox Code Playgroud)

而不是使用该对索引外部列表self.x, self.y-1.


Rik*_*ggi 5

问题来自你的self.room.

因为这个:

self.room[self.x, self.y-1]
Run Code Online (Sandbox Code Playgroud)

是相同的:

self.room[(self.x, self.y-1)]
Run Code Online (Sandbox Code Playgroud)

那是你的tuple错误.

有两种可能性:

请提供更多信息self.room.