A challenge in the beginner book "Automate the boring stuff":
#! Python3
# Table printer
# Takes a list of lists of strings and displays in right-justified table
# assumption is inner lists contain same number items
# each inner list must be printed as a column
the_list = [["a", "bbbbbbbbb", "tttt"],
["d", "eeee", "ggggggggggg"],
["g", "hhh", "kkkkkkkkkkkkkkkk"]]
def print_table(a_list):
"""
Prints a 2d list as a right justified table where each column represents
an inner list
"""
rows = len(the_list[0])
columns = len(the_list)
column_widths = [0 for i in range(columns)]
# find longest string in each inner lists(or column)
for i in range(len(column_widths)):
longest = 0
for item in a_list[i]:
if len(item) > longest:
longest = len(item)
column_widths[i] = longest
# store strings in list
print_row = ["" for i in range(rows)]
# iterate over lists to produce strings with correct formatting
for a in range(rows):
for i in range(columns):
print_row[a] = print_row[a] + a_list[i][a].rjust(column_widths[i]
+ 4)
for item in print_row:
print(item)
print_table(the_list)