I am learning python and have been presented with the following practice problem. I am trying to take the following list and print it in a right-justified table.
tableData= [['apples', 'oranges', 'cherries' , 'banana'],
['Alice' , 'Bob' , 'Carol', 'David'],
['dogs' , 'cats' , 'moose', 'goose']]
And the output should look like this.
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
Here is my code.
tableData= [['apples', 'oranges', 'cherries' , 'banana'],
['Alice' , 'Bob' , 'Carol', 'David'],
['dogs' , 'cats' , 'moose', 'goose']]
def printTable(lists):
colWidths = [0] * len(lists)
for x in range(0, len(lists[0])):
for y in range(0, len(lists)):
colWidths[y] = len(max(lists[y]))
fillChar= 0
fillChar = colWidths[x] - len(lists[y][x])
print(lists[y][x].rjust(fillChar, ' ' ) + ' ' , end = '' )
print(colWidths)
printTable(tableData)
The output I keep getting is below.
apples Alice dogs
oranges Bob cats
cherries Carol moose
Traceback (most recent call last):
File "/Users/DakotaDickey/Documents/Python Projects /Examples/PrintTable.py", line 36, in <module>
printTable(tableData)
File "/Users/DakotaDickey/Documents/Python Projects /Examples/PrintTable.py", line 17, in printTable
fillChar = colWidths[x] - len(lists[y][x])
IndexError: list index out of range
Thanks for all your help