我正在尝试检查一个位置,看看它周围的位置是否都是有效索引,以及在网格系统上是否在视觉上彼此相邻(因此是count_neighbor函数名称)。在第8行,我得到一个IndexError意味着if语句之前没有正确过滤掉无效和/或不在它正在测试的其他单元格旁边。我似乎无法弄明白为什么......
def count_neighbours(grid, row, col):
count = 0
neighbors = ((1,0),(1,-1),(1,1),
(0,1),(0,-1),
(-1,0),(-1,-1),(-1,1))
for x,y in neighbors:
if row+x >= 0 and col+y >= 0 and row+x < len(grid)-1 and col+y < len(grid)-1:
if grid[row+x][col+y] == 1:
count += 1
return count
print count_neighbours(((1,0,1,0,1),
(0,1,0,1,0),
(1,0,1,0,1),
(0,1,0,1,0),
(1,0,1,0,1),
(0,1,0,1,0)),5,4)
错误:
Traceback (most recent call last):
File "test.py", line 17, in <module>
(0,1,0,1,0)),5,4)
File "test.py", line 8, in count_neighbours
if grid[row+x][col+y] == 1:
IndexError: tuple index out of range
答案 0 :(得分:0)
你的if语句不够严格。目前正在使用or
:
if ((row+x >= 0 or col+y >= 0)
and
(row+x < len(grid)-1 or col+y < len(grid)-1)):
将or
更改为and
s:
if ((row+x >= 0 and col+y >= 0)
and
(row+x < len(grid)-1 and col+y < len(grid)-1)):