Other ways of doing matrix

1

I have been able to develop here, you should not print spaces after the last element of each line, which causes the exercise to go wrong, does anyone know of another method?

minha_matriz= [[1,2,3],[4,5,6],[7,8,9]]

def imprime_matriz(minha_matriz):
      for i in range(len(minha_matriz)):
             print(end="\n")
             for j in range(len(minha_matriz[i])):
                            print(minha_matriz[i][j], end =' ')
    
asked by anonymous 24.02.2017 / 16:48

1 answer

3

Yes. For example, this form:

def imprime_matriz(minha_matriz):
      for linha in minha_matriz:
        print(' '.join(str(i) for i in linha))

minha_matriz= [[1,2,3],[4,5,6],[7,8,9]]                            
imprime_matriz(minha_matriz)

You can see running on Ideone .

What happens is that in your code you print number by number and it tells the print function to "swap" the newline character (the famous '\n' ) by whitespace ( ' ' ). It does this for all elements, including the latter. You could do a check (a if ) to know when it is last and just in this case use end='' , but the most "pythonic" way is to use join . It will join the items in a list (the line inside the for) by separating them with the string data, without putting anything at the beginning or end of the result. :)

    
24.02.2017 / 17:01