【小练习】表格打印 printTable()
编写一个名为printTable() 的函数,它接受字符串的列表的列表,将它显示在组织良好的表格中,每列右对齐。假定所有内层列表都包含同样数目的字符串。例如,该值可能看起来像这样:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
你的printTable() 函数将打印出:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
colWidth = [0] * len(table) 创建了一个列表包含最大长度
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable(table):
colWidth = [0]*len(table) # 记录最大长度
max = 0
for i in range(len(colWidth)):
for j in range(len(table[0])):
if len(table[i][j]) > colWidth[i]:
max = len(table[i][j])
colWidth[i] = max
for m in range(len(table[0])):
for n in range(len(table)):
print(table[n][m].rjust(colWidth[n]), end = ' ')
print('\n',end = '')
printTable(tableData)
左右对齐均可( ljust / rjust)
左对齐:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
右对齐:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose