![](/img/trans.png)
[英]Python IndexError: list index out of range - 2d list iteration
[英]List index out of range in 2D list
我知道这里、 这里和 这里也有类似的问题。 第一个解决一维列表,第二个很好,但似乎不起作用,第三个很接近,但我仍然不太明白我的问题。
这就是我想要做的。 我需要创建一个用 0 填充的 2D 列表(Java 和 C++ 中的一个 2D 数组,我更熟悉)。 它的尺寸需要为 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
的整个源代码, isPointAccessible
错误消息看来,您的返回行必须是:
return self.grid[y][x] == 0
因为y
表示行号而x
是列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.