Home > Blockchain >  format multiple list of lists in a table vertically
format multiple list of lists in a table vertically

Time:03-26

I am new to formatting and trying to format multiple lists of list to be tidy. My code I have tried, which I have used for single list of lists is:

from tabulate import tabulate

orig = [['all', 4], ['away', 1], ['ball', 0], ['before', 1]]
first = [['every', 5], ['home', 1], ['game', 2], ['time', 2]]
second = [['one', 7], ['family', 1], ['sport', 3], ['now', 3]]
third = [['day', 10], ['friends', 1], ['game', 8], ['never', 3]]

print(tabulate([orig, first, second, third],  headers=['Orig', 'First', 'Second', 'Third']))

The problem I'm having is the rows and columns are reversed.

I want for example, Orig to be ['all', 4],['away', 1],['ball', 0],['before', 1]

Any help would be appreciated inc. other ideas.

Thanks in advance

CodePudding user response:

Cant you just use dictionaries?

orig = {"all": 4, "away": 1, "ball": 0, "before": 1}

# Keep in mind that to get the values you use the key. so:
# orig["all"] would give you 4
# iterating is also different
for key in orig:
    print(key, orig[key])
# this will give you the key and the value.

I hope this helps you, not sure if this will work in your specific situation, though, but you can try.

CodePudding user response:

You have to transpose the table. One way to do that is using zip:

print(
    tabulate(
        zip(orig, first, second, third),
        headers=['Orig', 'First', 'Second', 'Third']
    )
)

Result:

Orig           First         Second         Third
-------------  ------------  -------------  --------------
['all', 4]     ['every', 5]  ['one', 7]     ['day', 10]
['away', 1]    ['home', 1]   ['family', 1]  ['friends', 1]
['ball', 0]    ['game', 2]   ['sport', 3]   ['game', 8]
['before', 1]  ['time', 2]   ['now', 3]     ['never', 3]
  • Related