在本节中,他们希望我们创建此表:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
必须右对齐,输入为tableData。这是我的代码:
tableData=[['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
listlens=[]
tour=0
lists={}
for m in tableData:
total=0
tour+=1
for n in m:
total+=len(n)
lists["list:",tour]=total
print("list",tour,total)
itemcount=list(lists.values())
sortedlen=(sorted(itemcount,reverse=True))
longest=sortedlen[0]
#print (lists['list:', 1])
#print (longest)
for m in range(len(tableData[0])):
for n in range(len(tableData)):
print (tableData[n][m],end=" ")
n+=1
print ("".rjust(lists['list:', 1],"-"))
m+=1
除了一件事,我几乎完成了,我不能让它右对齐。这个输出是我到目前为止最接近的。
apples Alice dogs ---------------------------
oranges Bob cats ---------------------------
cherries Carol moose ---------------------------
banana David goose ---------------------------
如果我将 rjust 放在内部 for 循环中,输出就会大不相同:
apples-------------------------- Alice-------------------------- dogs--------------------------
oranges-------------------------- Bob-------------------------- cats--------------------------
cherries-------------------------- Carol-------------------------- moose--------------------------
banana-------------------------- David-------------------------- goose--------------------------
原文由 Stanley Wilkins 发布,翻译遵循 CC BY-SA 4.0 许可协议
这里有一个替代方法,也许您可以将其应用于您自己的代码。我首先将
tableData
整理成字典,以便于使用。之后我找到了最长的字符列表。这让我们知道较短的列表应该走多远。最后,我打印出每个列表,根据与最长列表的不同,在较短列表前添加空格。