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):
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With