简体   繁体   中英

Finding value in a matrix using python

I am getting the error 'int object is not iterable' on this method in my class. Someone assist me find the bug as I can't see what I am doing wrong

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

Example:

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

i, j = find(self, val)

print(i)
print(j)

Print: 1 2

If define self as matrix of 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

here is the part of your code that is causing the error

for i,j in range(3)

the python's built-in range function generates a sequence of number that are then assigned to one variable, but you're using two variables instead . This is how your code should be :

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM