wisnia
wisnia

Reputation: 85

Python - printing 2 dimensional array in columns

first time here.
I did a bit of searching on my own before posting a question, however,
I couldn't find the exact answer to it.
I've done such things before in C/C++ but here I'm a bit confused.

I want to print this :

table = [ ['A','B','C','D'], ['E','F','G','H'], ['I','J','K','L'] ]

this way:

'A'   'E'   'I'  
'B'   'F'   'J'  
'C'   'G'   'K'  
'D'   'H'   'L'  

automatically, in a loop.
First variable from every table in first row, second in second row, etc...
I tried with 2 for loops but I'm doing it wrong because I run out of indexes.

EDIT - this part is solved but one more question

I have:

tableData = [ ['apple', 'orange', 'cherry', 'banana'],  
              ['John', 'Joanna', 'Sam', 'David'],  
              ['dog', 'cat', 'mouse', 'rat'] ]  

and it has to look like this:

|   apple   |  John  |  dog  |  
|   orange  | Joanna |  cat  |
|  cherry   |  Sam   | mouse |
|  banana   | David  |  rat  |  

"function should be able to manage lists with different lengths and
count how much space is needed for a string (for every column separately)".
Every string has to be centered in it's column.

I tried to print previous table having a zipped object

for row in zip(*table):
    print('| ', ' | '.join(row), ' |')  

|  A | E | I  |
|  B | F | J  |
|  C | G | K  |
|  D | H | L  |  

but I am out of ideas what comes next in this situation

Upvotes: 3

Views: 6194

Answers (2)

Chris Howe
Chris Howe

Reputation: 213

Here you go this works regardless of what the information in the list is.

table = [["a","b","c","d"],["e","f","g","h"],["i","j","k","l"]]
max = len(table[0])
max2 = len (table)
string = []

for a in range(0,max):
    for b in range(0,max2):
        if len(string) == max2:
            string = []
        string.append(table[b][a])
    print string

Upvotes: 1

alecxe
alecxe

Reputation: 474131

You can zip(), str.join() and print:

In [1]: table = [ ['A','B','C','D'], ['E','F','G','H'], ['I','J','K','L'] ]

In [2]: for row in zip(*table):
   ...:     print(" ".join(row))
   ...:     
A E I
B F J
C G K
D H L

Or, a one-liner version joining the rows with a newline character:

>>> print("\n".join(" ".join(row) for row in zip(*table)))
A E I
B F J
C G K
D H L

Upvotes: 9

Related Questions