Python矩阵邻居检查 [英] Python Matrix Neighbor Checking

查看:112
本文介绍了Python矩阵邻居检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含0和1的7 * 7矩阵,其中将检查每个(x,y)的邻居数是否为1.我是python的初学者,并且只会使用基本的编程过程.

I have a 7*7 matrix containing 0s and 1s in which each (x,y) will be checked for how many of its neighbors are a 1. I am a beginner to python, and will only be using basic programming procedures.

我有:

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

I am getting the ol indexing error. This seems like a very simple problem I just can't seem to figure out how to fix it.

推荐答案

首先,执行y + 1时发生索引错误.由于您要输入的列数为cols,因此最终将为cols + 1,超出范围. 您可以做的是使用try-except块,或者通过仅循环到cols-1来确保它不会超出范围.

First of all, the index error occurs when you do y+1. Since you are going in the range of the amount of cols, this will end up being cols+1, which is out of range. What you can do is use a try-except block, or make sure it doesn't get out of range through only looping to cols-1.

另外,您的函数定义是多余的,因为您没有使用所有的输入参数,并且在全局作用域中访问x和y变量. 最简单的操作可能就是删除定义和返回语句.

Additionally your function definition is redundant, since you don't use all your input parameters, and you access the x and y variables in the global scope. The easiest thing to do is probably just to remove the definition and the return-statement.

这应该有效:

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

这篇关于Python矩阵邻居检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆