Matrix Python矩阵邻居检查
我有一个包含0和1的7*7矩阵,其中每个(x,y)都将检查其有多少个邻居是1。我是python的初学者,将只使用基本的编程程序 我有:Matrix Python矩阵邻居检查,matrix,python-3.x,Matrix,Python 3.x,我有一个包含0和1的7*7矩阵,其中每个(x,y)都将检查其有多少个邻居是1。我是python的初学者,将只使用基本的编程程序 我有: for x in range(rows): for y in range(cols): lives = 0 lives = neighbors(matrix, rows, cols) def neighbors(matrix, rows, cols): if matrix
for x in range(rows):
for y in range(cols):
lives = 0
lives = neighbors(matrix, rows, cols)
def neighbors(matrix, rows, cols):
if matrix[x][y+1] == 1:
lives += 1
if matrix[x-1][y+1] == 1:
lives += 1
#All 8 positions are checked like this
return lives
我得到了ol索引错误。这似乎是一个非常简单的问题,但我似乎不知道如何解决它 首先,执行y+1时会出现索引错误。因为你是在cols的数量范围内,这将是cols+1,这超出了范围。 您可以使用try-except块,或者通过只循环到cols-1来确保它不会超出范围 此外,函数定义是多余的,因为您不使用所有的输入参数,并且可以访问全局范围内的x和y变量。 最简单的方法可能就是删除定义和return语句 这应该起作用:
for x in range(rows):
for y in range(cols-1): #Loop until the second to last element.
lives = 0
if matrix[x][y+1] == 1:
lives += 1
if x == 0: #You probably don't want to check x-1 = -1
continue
if matrix[x-1][y+1] == 1:
lives += 1
谢谢我知道我忽略了一些简单的事情。我让它工作了。