我知道有类似的问题here , here , 和 here .第一个解决一维列表,第二个很好,但它似乎不起作用,第三个很接近,但我仍然不太明白我的问题。
这是我正在尝试做的事情。我需要创建一个 2D 列表(Java 和 C++ 中的 2D 数组,我更熟悉),其中填充了 0。它的尺寸必须是 20 号横宽 15 号宽。
这是我尝试过的:
self.grid = [[0 for x in range(GRID_COLUMN_SIZE)] for y in range(GRID_ROW_SIZE)] # where GRID_ROW_SIZE = 15, GRID_COLUMN_SIZE = 20
请注意,我尝试切换两个常量(先是COLUMN,然后是ROW),但稍晚一点就坏了。此外,我打印了 2D 列表,它的尺寸错误(横向 15,向下 20)。
这里是我后来使用的self.grid。在不深入的情况下,我将遍历列表 (grid) 的所有值并获取周围的点。
def populatePaths(self):
for row in range(len(self.grid)):
for column in range(len(self.grid[row])):
if self.isPointAccessible(column, row):
self.addPaths(column, row)
def addPaths(self, x, y):
key = Point(x, y)
print "Each: %s" % (key.toString())
points = key.getSurroundingPoints()
self.removeBarriersFromPath(points)
self.paths[key] = points # a map from Points to lists of surrounding Points
基本上,我删除了路径上无法到达的点:
def removeBarriersFromPath(self, path):
for point in list(path):
print "Surrounding %s" % (point.toString())
if not self.isPointAccessible(point.x, point.y):
path.remove(point)
return path
self.isPointAccessible() 是微不足道的,但这就是它的问题所在。它检查 (x,y) 位置的值是否为 0:return self.grid[x][y] == 0
我添加了这些打印语句(point.toString() 返回 (x,y))来显示发生的点,并且我能够迭代直到 x==14,但它在 x==15 处中断。
我怀疑我在循环中得到的列/行顺序不正确,但我不确定何时/如何。
如果我解释得不够清楚,请告诉我。
编辑 这是追溯:
Traceback (most recent call last):
File "/home/nu/catkin_ws/src/apriltags_intrude_detector/scripts/sphero_intrude_gui.py", line 70, in start
self.populatePaths()
File "/home/nu/catkin_ws/src/apriltags_intrude_detector/scripts/sphero_intrude_gui.py", line 156, in populatePaths
self.addPaths(column, row)
File "/home/nu/catkin_ws/src/apriltags_intrude_detector/scripts/sphero_intrude_gui.py", line 162, in addPaths
self.removeBarriersFromPath(points)
File "/home/nu/catkin_ws/src/apriltags_intrude_detector/scripts/sphero_intrude_gui.py", line 168, in removeBarriersFromPath
if not self.isPointAccessible(point.x, point.y):
File "/home/nu/catkin_ws/src/apriltags_intrude_detector/scripts/sphero_intrude_gui.py", line 173, in isPointAccessible
return self.grid[x][y] == 0
IndexError: list index out of range
请您参考如下方法:
您没有发布 isPointAccessible 的完整源代码,但从错误消息看来您的返回行必须是:
return self.grid[y][x] == 0
因为 y 表示行号而 x 是列。
