练习题要求我将 tabledata 中的嵌套列表排列成右对齐列,每个列都有一个嵌套列表。我已经想出了如何将每列中的每个单词正确对齐到列本身的正确长度,但我不知道如何将列连接到列表中,而不是仅仅将它们打印为一列。
for我已经尝试通过提前迭代来连接 -loop 中的字符串( print(list[i]+list[i+1]+list[i+2]...etc),但是index out of range当它再次循环并递增i.
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def longlen(strings):
maximum = 0
for s in strings:
if len(s) > maximum:
maximum = len(s)
return(maximum)
def printTable(table):
column_width = [0] * len(table)
for i in range(len(table)):
column_width[i] =longlen(table[i])
for x in range(len(table[i])):
print(table[i][x].rjust(column_width[i]))
printTable(tableData)
现在我得到了每个单词的正确右对齐,但我不知道如何在一个 4 高 x 3 宽的右对齐表格中输出它。
现在它看起来像这样:
apples
oranges
cherries
banana
Alice
Bob
Carol
David
dogs
cats
moose
goose
我需要这个:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose