Print multi-dimensional array in Python

0

I'm in doubt about how to create a function ( imprime_matriz ) that receives an array as a parameter and prints the array row by row. Note: Spaces after the last element of each line should not be printed. Can anyone help me?

The code I tried was this:

def cria_matriz(num_linhas, num_colunas):

    matriz = []
    for i in range(num_linhas):
        linha = []
        for j in range(num_colunas):
            valor = int(input("Digite o elemento [" + str(i) + "][" + str(j) + "]"))
            linha.append(valor)

        matriz.append(linha)
    return matriz


def le_matriz():
    lin = int(input("Digite o número de linhas da matriz: "))
    col = int(input("Digite o número de colunas da matriz: "))
    return cria_matriz(lin, col)

m = le_matriz()

Option 2: (shorter)

def imprime_matriz(matriz):

linhas = len(matriz)
colunas = len(matriz[0])

for i in range(linhas):
    for j in range(colunas):
        if(j == colunas - 1):
            print("%d" %matriz[i][j], end = "")
        else:
            print("%d" %matriz[i][j], end = "")
print()
    
asked by anonymous 05.02.2017 / 17:03

2 answers

1

For your code, your arrays will be two-dimensional, since you are only asked to enter two-dimensional size. So you can use the code below.

for linha in m:
    for val in linha:
        print '{:4}'.format(val),
    print

It has output.

Digite o numero de linhas da matriz:2
Digite o numero de colunas da matriz: 2
Digite o elemento [0][0]1
Digite o elemento [0][1]2
Digite o elemento [1][0]3
Digite o elemento [1][1]4
   1    2
   3    4

You can see the code working at ideone or here .

Note that the code depends on the size of the array, the more dimensions, the more links you will need.

To print independent arrays of the dimension, use the NumPy

As in the example below

import numpy as np

m1 = [[1], [2], [3]]
m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print (np.matrix(m))
print
print (np.matrix(m2))

which generates the following output

[[1]
 [2]
 [3]]

[[1 2 3]
 [4 5 6]
 [7 8 9]]

EDIT I add below image with output testing the step code and the 3 test prints.

.

    
05.02.2017 / 17:38
1

Good afternoon, I used your own example to solve your problem. I hope I have helped.

Example

Entry: matrix = [[1, 2, 3], [4, 5, 6], [7,8,9]]

Output:

1 2 3

4 5 6

7 8 9

Function:

def imprime_matriz(matriz):

    linhas = len(matriz)
    colunas = len(matriz[0])

    for i in range(linhas):
        for j in range(colunas):
            if(j == colunas - 1):
                print("%d" %matriz[i][j])
            else:
                print("%d" %matriz[i][j], end = " ")
    print()
    
15.02.2017 / 19:20