Error trying to print an array with larger elements from two other matrices - 'int' Object is not subscriptable

Asked

Viewed 41 times

1

In my code, I create two matrices, and compare the elements of the two in each position. The largest element at each position is selected and placed in the third matrix. When I finish all the checking, I have the loop to print the third matrix, however, I get the error of Typeerror: 'int' Object is not subscriptable - in the loop print code line:

for i in range(4):
    print(m3[i])

My complete code below:

m1 = []
m2 = []
m3 = []

for i in range(4):
    linha = []
    for j in range(4):
        linha.append(int(input('Primeira Matriz - Insira o valor ['+ str(i) +','+ str(j) +']:')))
    m1.append(linha)
for i in range(4):
    linha = []
    for j in range(4):
        linha.append(int(input('Segunda Matriz - Insira o valor ['+ str(i) +','+ str(j) +']:')))
    m2.append(linha)
maior = 0
for i in range(4):
    for j in range(4):
         if m1[i][j] > m2[i][j]:
             m3 = m1[i][j]
         else:
            m3 = m2[i][j]
for i in range(4):
    print(m3[i])

1 answer

1


When you do m3 = m1[i][j], the variable m3 is receiving a number. That is, it is no longer a list, and therefore it has no positions to access. Hence the error "'int' Object is not subscriptable", to do m3[i] when m3 is a number does not work.

What you need to do is go adding the rows and columns in m3:

m3 = []
for i in range(4):
    linha = []
    for j in range(4):
         if m1[i][j] > m2[i][j]:
             linha.append(m1[i][j])
         else:
             linha.append(m2[i][j])
    m3.append(linha)

Although you can go through m1 and m2 at the same time using zip, and use max to obtain the largest of the elements:

m3 = []
for linha1, linha2 in zip(m1, m2):
    linha = []
    for e1, e2 in zip(linha1, linha2):
        linha.append(max(e1, e2))
    m3.append(linha)

At every iteration, linha1 is one of the lines of m1 and linha2 is one of the lines of m2. Then I run these lines at the same time (also using zip, thus at each iteration, e1 is an element of linha1 and e2 is an element of linha2) and add the largest among these elements in the line.

The loop above can also be replaced by a comprehensilist on, much more succinct and pythonic:

m3 = [
   [ max(e1, e2) for e1, e2 in zip(linha1, linha2) ]
   for linha1, linha2 in zip(m1, m2)
]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.