【问题标题】:Python Matrix Neighbor CheckingPython 矩阵邻居检查
【发布时间】:2012-11-29 08:30:23
【问题描述】:

我有一个包含 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[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 索引错误。这似乎是一个非常简单的问题,我似乎无法弄清楚如何解决它。

【问题讨论】:

    标签: matrix python-3.x


    【解决方案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
    

    【讨论】:

    • 谢谢!我知道我忽略了一些简单的事情。我得到了它的工作。
    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2022-11-16
    • 2021-08-30
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多