Other ways to make matrix

Asked

Viewed 55 times

1

I managed to develop so far, you should not print spaces after the last element of each line which makes the exercise go wrong, someone knows 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 =' ')

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 in Ideone.

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

  • 1

    Thank you so much for your reply, gave me a floor ... VLW

  • Not at all. : ) If the answer was helpful, please consider mark her as accepted.

  • Could you help me with this exercise ? http://answall.com/questions/186090/operator-subtract%C3%A7%C3%A3o-n%C3%A3o-recognized-no-python

Browser other questions tagged

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