6

I have this list of lists:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

that i have to transform into this table:

apples      Alice    dogs
oranges       Bob    cats 
cherries    Carol    moose 
banana      David    goose

The trick for me, is have the "lines" to be converted into columns (i.e. apples, oranges, cherries, banana under same column)

I have tried different options (A):

for row in tableData:
        output = [row[0].ljust(20)]
            for col in row[1:]:
             output.append(col.rjust(10))
            print(' '.join(output))

option (B):

method 2

for i in tableData:
    print( i[0].ljust(10)+(str(i[1].ljust(15)))+(str(i[2].ljust(15)))+
    (str(i[3].ljust(15))))    

None seems to address the issue.
Thanks in advance for any suggestions.

3
  • Just to be clear, is this Py2 or Py3? print differs from one to the other, and the way your example code uses it doesn't exercise any of the differences to make that clear. Commented Sep 6, 2016 at 22:56
  • Also: Python: Printing Lists as Tabular Data Commented Sep 7, 2016 at 6:47
  • this is python 3.5 Commented Sep 7, 2016 at 14:22

4 Answers 4

8

To transpose the table, use the zip-and-splat trick.

To left-or-right-justify cells, use the format spec language:

>>> for row in zip(*tableData):
...     print '{:<10}{:>7}    {:<10}'.format(*row)
...     
apples      Alice    dogs      
oranges       Bob    cats      
cherries    Carol    moose     
banana      David    goose   
Sign up to request clarification or add additional context in comments.

3 Comments

No need for explicit field width on the final entry, since it's left justified and will spill if it exceeds the width anyway. Otherwise, yeah, best answer.
thank you. what exactly do these #'s represent
Did you follow the link? The numbers are the space that is reserved for the content so that left-or-right-justify knows how many spacess have to be added on the left or right side.
2

One could also play around with pandas.DataFrame:

In [22]: import pandas as pd
In [22]: pd.DataFrame(tableData).T # .T means transpose the dataframe
Out[22]:
          0      1      2
0    apples  Alice   dogs
1   oranges    Bob   cats
2  cherries  Carol  moose
3    banana  David  goose

Remove those annoying numbers by setting columns and indices to blank:

In [27]: l1, l2 = len(tableData), len(tableData[0])

In [28]: pd.DataFrame(tableData, index=['']*l1, columns=['']*l2).T
Out[28]:

    apples  Alice   dogs
   oranges    Bob   cats
  cherries  Carol  moose
    banana  David  goose

2 Comments

Not downvoting, but I think whipping out pandas for a simple problem might be overdoing it, just a bit. :-)
@ShadowRanger I did considered that, but on a second thought I think it's a tool worth considering by the questioner (if not now, in the long run) :)
1

The easiest way to "flip" the nested list is to use zip:

for fruit, name, animal in zip(*tableData):
    print(fruit.ljust(10), name.ljust(10), animal.ljust(10))

This prints:

apples     Alice      dogs
oranges    Bob        cats
cherries   Carol      moose
banana     David      goose

1 Comment

amazing!!!. Thank you
0

There is already a builtin function for this: zip.

zip(* [['apples', 'oranges', 'cherries', 'banana'],
       ['Alice', 'Bob', 'Carol', 'David'],
       ['dogs', 'cats', 'moose', 'goose']])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.