我尝试做的是拥有一个2D数组,并且对于数组中的每个坐标,如果它们存储了1或0,则询问它周围的所有其他8个坐标。类似于寻找地雷的扫雷
我以前有这个:
grid = []
for fila in range(10):
grid.append([])
for columna in range(10):
grid[fila].append(0)
#edited
for fila in range (10):
for columna in range (10):
neighbour = 0
for i in range 10:
for j in range 10:
if gird[fila + i][columna + j] == 1
neighbour += 1
但有些事情并不顺利。我也有打印声明试图找到错误,但我仍然不明白为什么它只有一半的for循环。所以我将第二个for循环更改为:
#edited
for fila in range (10):
for columna in range (10):
neighbour = 0
if grid[fila - 1][columna - 1] == 1:
neighbour += 1
if grid[fila - 1][columna] == 1:
neighbour += 1
if grid[fila - 1][columna + 1] == 1:
neighbour += 1
if grid[fila][columna - 1] == 1:
neighbour += 1
if grid[fila][columna + 1] == 1:
neighbour += 1
if grid[fila + 1][columna - 1] == 1:
neighbour += 1
if grid[fila + 1][columna] == 1:
neighbour += 1
if grid[fila + 1][columna + 1] == 1:
neighbour += 1
得到了这个错误:
if grid[fila - 1][columna + 1] == 1:
IndexError: list index out of range
似乎我无法添加网格坐标,但我可以减去。那是为什么?
答案 0 :(得分:0)
python中的有效索引是-len(grid)
到len(grid)-1
。正指数是从前面偏移的元素,从后面偏移的元素。如果索引大于您所看到的len(grid)-1
,则添加会给出范围错误。除非得到的索引值小于-len(grid)
,否则减法不会给出范围错误。虽然你没有检查下限,即0(零)它似乎适合你,因为小的负指数从后端返回你的值。这是一个导致错误邻居结果的无声错误。
答案 1 :(得分:0)
如果要计算偏移量,则需要确保偏移量在列表的范围内。因此,如果您有10个元素,请不要尝试访问第11个元素。
import collections
grid_offset = collections.namedtuple('grid_offset', 'dr dc')
Grid = [[0 for c in range(10)] for r in range(10)]
Grid_height = len(Grid)
Grid_width = len(Grid[0])
Neighbors = [
grid_offset(dr, dc)
for dr in range(-1, 2)
for dc in range(-1, 2)
if not dr == dc == 0
]
def count_neighbors(row, col):
count = 0
for nb in Neighbors:
r = row + nb.dr
c = col + nb.dc
if 0 <= r < Grid_height and 0 <= c < Grid_width:
# Add the value, or just add one?
count += Grid[r][c]
return count
Grid[4][6] = 1
Grid[5][4] = 1
Grid[5][5] = 1
for row in range(10):
for col in range(10):
print(count_neighbors(row, col), "", end='')
print()
打印:
$ python test.py
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 1 1 0 0
0 0 0 1 2 3 1 1 0 0
0 0 0 1 1 2 2 1 0 0
0 0 0 1 2 2 1 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
答案 2 :(得分:-1)
错误正是它所说的,你需要检查坐标是否适合网格:
0 <= i < 10 and 0 <= j < 10
否则,您尝试访问内存中不存在的元素,或者不是您实际想到的元素 - Python处理负面索引,它们和&# #39;从最后算起。
E.g。 a[-1]
是最后一个元素,与a[len(a) - 1]
完全相同。