The project outline:
Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified. Assume that all the inner lists will contain the same number of strings.
My code:
def demo():
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David',],
['dogs', 'cats', 'moose', 'goose']]
return tableData
def printTable(tableData):
colWidths = [0] * len(tableData)
for i in range(len(tableData)):
colWidths[i] = len(max(tableData[i], key=len))
for x in range(len(tableData[0])):
for y in range(len(tableData)):
print(tableData[y][x].rjust(colWidths[y]), end=' ')
print(end='\n')
printTable(demo())
This took me a while to get my head around. I ended up using max()
which the book hasn't covered yet but otherwise I think this is what the author had in mind.
Ways to make it better?
print('\n'.join(' | '.join(row)for row in zip(*((word.rjust(width)for word in col)for col,width in zip(tableData,(max((len(word)for word in col))for col in tableData))))))
\$\endgroup\$