使用python在矩阵中查找值

时间:2017-12-12 12:48:11

标签: python methods

我在我的课程中遇到此方法的错误'int object is iterable'。有人帮我找到了虫子,因为我看不出我做错了什么

def find(self, val): #finds value in matrix
    if 0 <= val <= 8:
        for i,j in range(3):
            #for j in range(3):
            if self.matrix[i][j] == val:
               return i, j
    return None 

2 个答案:

答案 0 :(得分:1)

def find(self, val):  # finds value in matrix
if 0 <= val <= 8:
    for i in range(3):
        for j in range(3):
            if self[i][j] == val:
                return i, j
return None

示例:

self = [[2,1,2],[1,6,4],[0,0,2]]
val = 4

i, j = find(self, val)

print(i)
print(j)

打印: 1 2

如果将self定义为numpy的矩阵:

def find(self, val):  # finds value in matrix
    if 0 <= val <= 8:
        for i in range(3):
            for j in range(3):
                if self.item((i, j)) == val:
                    return i, j
    return None

答案 1 :(得分:0)

这是导致错误的代码部分

for i,j in range(3)

python的内置范围函数会生成一个数字序列,然后将其分配给一个变量,但是您将使用两个变量来代替 。这就是您的代码应该如何:

def find(self, val): #finds value in matrix
    if 0 <= val <= 8:
        for i in range(3):
            for j in range(3):
                if self.matrix[i][j] == val:
                    return i, j
    return None