![](/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.