I'm trying to do one of the practice projects of How to automate the boring stuff. But I'm stuck.
Essentially, when given a list like:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
the program is supposed to print out the following table, where each column is right justified:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
This is my code:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable():
colWidths = [0] * len(tableData)
for index in range(len(tableData)):
colWidths[index] = len(max(tableData[index], key = len))
for index in range(len(tableData)):
for element in tableData[index]:
print(element.rjust(colWidths[index]))
printTable()
My problem is that each one of the lists gets properly right justified, but everything is printed out in a single column, not a table, like this:
apples
oranges
cherries
banana
Alice
Bob
Carol
David
dogs
cats
moose
goose
Is there any way I can add a new column after each iteration of the for loop? Or how would you improve my code?
Thank you for your help!