代码如下:
题目的意思是通过一个函数将列表的列表显示在组织良好的表格中,每列右对齐
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
'''
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
'''
#输出每一列右对齐 我想不应该是字符串最后一个对齐么,
#但是书上的不是啊,困扰了我一晚上
def printTable(tableData):
colWidths = [0] * len(tableData)
col = []
for i in range(0, len(tableData[0])):
for j in range(0, len(colWidths)):
col.append(len(tableData[j][i]))
max_len = max(col)
for i in range(0, len(tableData[0])):
for j in range(0, len(colWidths)):
print(tableData[j][i].rjust(max_len),end='')
print()
if __name__ == '__main__':
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
printTable(tableData)
----------------------------------------------------------------
----------------------------------------------------------------
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
每一列右对齐只能是这样,想不到更好的解决,如果有大神知道怎么解决请留言