【发布时间】:2020-07-25 15:13:37
【问题描述】:
这个程序的目标是接收一个名为 tableData 的嵌套列表,并编写一个函数来显示右对齐的有组织的列。该功能适用于代码,但我想获得一些反馈或知道我是否可以更有效地解决未来的问题。
苹果爱丽丝狗
橘子鲍勃猫
樱桃卡罗尔驼鹿
香蕉大卫鹅
tableData = [['apples','oranges','cherries','banana'],
['Alice','Bob','Carol', 'David'],
['dogs', 'cats','moose','goose']]
def printTable():
colWidths = [0]* len(tableData)
one = []
two = []
three = []
for i in range(len(tableData)):
colWidths[i] = tableData[i]
place = tableData[i]
for x in range(len(tableData[i])):
spot = colWidths
if len(one) < len(place):
one.append(colWidths[i][x])
elif len(two) < len(place):
two.append(colWidths[i][x])
elif len(three) < len(place):
three.append(colWidths[i][x])
for i in range(len(one)):
print((one[i]+' ' +two[i]+ ' ' +three[i]).center(20,))
printTable()
【问题讨论】:
-
您可能想在 CodeReview (codereview.stackexchange.com) 尝试一下,这是获取改进工作代码提示的好地方。
-
如果您正在寻找现成的解决方案,我已经成功使用
tabulate模块 (github.com/astanin/python-tabulate)。它包含在 Anaconda 中,如果您不想使用 pip,可以在 Debian 存储库中找到它。
标签: python nested-lists