大家好,我是python学习新手,我在一个练习题目中遇到问题.
题目的要求是把列表打印输出并对齐。
输入数据:
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
以下是我的代码
"""下面是代码正文"""
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable(tableData):
# 下面是为了求每个内层列表的最长字符串的长度
colWidths = [0] * len(tableData)
for i in range(len(colWidths)):
colWidths[i] = len(sorted(tableData[i], key=(lambda x: len(x)))[-1])
for x in range(len(tableData[0])):
for y in range(len(tableData)):
print(tableData[y][x].rjust(colWidths[y]), end=' ')
print('') # 换行
printTable(tableData)
输出结果是(全部右对齐了):
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
请问要怎么做才能达到题目要求的输出结果?