Search code examples
pythonarraysloopsprintingdimensions

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


Solution

  • 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