我正在研究在 8 x 8 的 2d 网格房间周围移动机器人,其中一部分是初始化由机器人周围最近的 5 个方块组成的传感器。
self.sensors = [0 for x in xrange(5)]
这里我创建了一个包含 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]
我收到“列表索引必须是整数,而不是元组”的错误。
你说
self.room
是一个“二维网格”——我认为它是一个列表列表。在这种情况下,您应该访问其元素:
self.room[self.x][self.y-1]
而不是使用对
self.x, self.y-1
来索引外部列表。
问题来自于你的
self.room
。
因为这个:
self.room[self.x, self.y-1]
与以下相同:
self.room[(self.x, self.y-1)]
这就是你的
tuple
错误。
有两种可能:
self.room
是一个 2D 数组,这意味着您可能的意思是:
self.room[self.x][self.y-1]
你想切片
self.room
:
self.room[self.x:self.y-1]
请提供更多有关
self.room
的信息。
self.room[self.x, self.y-1]
使用元组索引 self.room
。如果它是一个参差不齐的数组,那么您必须使用 self.room[self.x][self.y-1]
代替。
self.room 的类型是什么,我认为 room 是一个列表,在这种情况下你必须像这样分配
if self.heading == 'East':
self.sensors[0] = [self.x, self.y-1]
或者像这样
if self.heading == 'East':
self.room = [self.x, self.y-1]
self.sensors[0] = self.room
像这样
>>> a = []
>>> type(a)
<type 'list'>
>>> a[2,3]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: list indices must be integers
>>> a = [2,3]
为什么会出现这个错误?我不会传递任何元组!
因为
__getitem__
处理 []
分辨率,将 self.room[1, 2]
转换为元组:
class C(object):
def __getitem__(self, k):
return k
# Single argument is passed directly.
assert C()[0] == 0
# Multiple indices generate a tuple.
assert C()[0, 1] == (0, 1)
并且列表并不是为了处理此类争论而创建的。
这是因为列表索引必须是整数,而不是其他任何值。就您而言,您正在尝试使用元组。
您的代码特别奇怪,因为您无法使用元组索引创建
self.room
。