Here's single direction to do this in plain Python. We can use zip to transpose the table so we can get the most extreme width of every column.
table_data = [
['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose'],
]
# Determine the width of each column
widths = [max(map(len, column)) for column in zip(*table_data)]
new_table = [[s.rjust(w) for s, w in zip(row, widths)]
for row in table_data]
for row in new_table:
print(row)
output:
['apples', 'oranges', 'cherries', 'banana']
[' Alice', ' Bob', ' Carol', ' David']
[' dogs', ' cats', ' moose', ' goose']
In the event that you don't actually require another 2D list, and you simply need to print the data, you can accomplish something like this:
for row in table_data:
print(*(s.rjust(w) for s, w in zip(row, widths)))
output:
apples oranges cherries banana
Alice Bob Carol David
dogs cats moose goose
Look at this new version which will transpose the table
widths = [max(map(len, row)) for row in table_data]
new_table = [[s.rjust(w) for s, w in zip(row, widths)] for row in zip(*table_data)]
for row in new_table:
print(row)
output:
[' apples', 'Alice', ' dogs']
[' oranges', ' Bob', ' cats']
['cherries', 'Carol', 'moose']
[' banana', 'David', 'goose']
Interested to learn python in detail? Come and Join the python course.
To know more about this you can have a look at the following video tutorial:-