3

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

1
  • That edit is big enough that you really should put that in a new question, and accept what you got for the first. The edit requires another iteration to figure out column widths, and the use of string formatting to center to strings with the fields. So it's not just a matter of extending all the joins. Commented Jan 8, 2017 at 0:08

2 Answers 2

9

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
Sign up to request clarification or add additional context in comments.

1 Comment

Nice one-liner. Could we use col rather row here? ;-)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.