Skip to content Skip to sidebar Skip to footer

Converting List Of Lists Into A Table

I have this list of lists: tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose'

Solution 1:

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

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

>>>for row inzip(*tableData):...print'{:<10}{:>7}    {:<10}'.format(*row)...
apples      Alice    dogs      
oranges       Bob    cats      
cherries    Carol    moose     
banana      David    goose   

Solution 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]:
          0120    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

Solution 3:

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

Solution 4:

There is already a builtin function for this: zip.

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

Post a Comment for "Converting List Of Lists Into A Table"