Display array in python

-1

I have an array of n by n and use this part of code to display it:

for i in range(len(data)):
    for j in range(len(data[0])):
        print ((data[i][j]))

Being data the matrix. But the output looks like this:

 5
 4
 1
10
 2
 3
 0
 2
 1
...

The values of data are coming from here

    data = [ [-1 for i in range(vertice)] for j in range(vertice)]
    for i in range(vertice):
        for j in range(vertice):
            if data[i][j] < 0:
                data[i][j] = random.randint(0, vertice)
                data[j][i] = random.randint(0, vertice)
            if i == j:
                data[i][i] = 0

    return data

I would like to present this way:

5 4 1 10 2
3 0 2  1 7 
3 0 2  1 7 
3 0 2  1 7 

I've tried a thousand and one ways, but I'm not getting there. What am I doing wrong?

    
asked by anonymous 22.11.2018 / 19:53

2 answers

2

First, never go through a Python list with for i in range(len(data)) and then data[i] . This is not idiomatic ( pythonic). You can simply make a for linha in data .

data = [
    [5, 4, 1, 10, 2],
    [3, 0, 2,  1, 7],
    [3, 0, 2,  1, 7],
    [3, 0, 2,  1, 7]
]

for linha in data:
    for numero in linha:
        print(numero, end=" ")
    print()

The problem is that because 10 has more characters than the others, the output will be:

5 4 1 10 2 
3 0 2 1 7 
3 0 2 1 7 
3 0 2 1 7 

You can work around this by formatting the output:

for linha in data:
    for numero in linha:
        print(f'{numero:>3}', end=" ")
    print()

Notice that instead of displaying only numero I displayed {numero:>3} . This will always display 3 characters and the number will be right-aligned:

  5   4   1  10   2 
  3   0   2   1   7 
  3   0   2   1   7 
  3   0   2   1   7 

Solve the problem for 10, but what if 9999 is in the array? This I leave to you to resolve.

    
22.11.2018 / 20:14
1

From what I understand you want to display the array in a way that is friendlier by separating in rows into columns, you can do as follows:

for i in range(len(data)):
    for j in range(len(data[0])):
       print ((data[i][j]), end=" ")
    print()

Python by default, adds a line break at the end of the print, so for the lines the end parameter to allocate a space, instead a line break, already, the other print has the function to break the line whenever a row of the array is fully displayed.

Output:

0 1 2 3 4 
1 2 3 4 5 
2 3 4 5 6 
3 4 5 6 7 
4 5 6 7 8 
    
22.11.2018 / 20:05