Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting list of lists into a table [duplicate]

Tags:

python

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.

like image 205
AT_1965 Avatar asked Dec 24 '22 01:12

AT_1965


2 Answers

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   
like image 58
wim Avatar answered Dec 26 '22 15:12

wim


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
like image 43
Moses Koledoye Avatar answered Dec 26 '22 15:12

Moses Koledoye