2012-11-29 135 views
2

我有一个7 * 7矩阵包含0和1,其中每个(x,y)将被检查其多少个邻居是1.我是一个Python初学者,并且只会是使用基本的编程程序。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[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索引错误。这似乎是一个非常简单的问题,我似乎无法弄清楚如何解决它。

回答

1

首先,当您执行y + 1时会发生索引错误。由于你正在进入cols的数量范围,所以最终会出现cols + 1,这超出了范围。 你可以做的是使用一个try-except块,或者确保它只通过循环到cols-1不会超出范围。

此外,您的函数定义是多余的,因为您不使用所有的输入参数,而是访问全局范围内的x和y变量。 最简单的做法可能只是删除定义和返回语句。

这应该工作:

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 
+0

谢谢!我知道这很简单,我忽略了。我得到了它的工作。 – user1862529