Python嵌套列表:表打印机函数



这个程序的目标是接收一个名为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() 

Python有一个名为zip的内置方法,它允许我们将可迭代项组合到一个变量中。如果您将此功能与Python的unpacking功能相结合,代码将变得非常精简。

tableData = [['apples','oranges','cherries','banana'],
['Alice','Bob','Carol', 'David'],
['dogs', 'cats','moose','goose']]
things = list(zip(*tableData))
for tuple in things:
print('{} {} {}'.format(*tuple).rjust(20))

我们在这里所做的是获取tabledata,并使用解包器*对其进行拆分,然后对其进行压缩,从而获得一个元组,其中包含分离列表中的每个值中的一个。

然后,我们通过things进行迭代,并再次使用解包来拆分每个元组。最后,我们可以使用rjust()来证明的正确性

您可以尝试下面的-,而不是尝试循环

import pandas as pd
tableData = [['apples','oranges','cherries','banana'],
['Alice','Bob','Carol', 'David'], 
['dogs', 'cats','moose','goose']]
df = pd.DataFrame(tableData)
df_transpose = df.transpose()

df_transpose['final'] = df_transpose.apply(lambda x: ' '.join(x.dropna().values.tolist()), axis=1)
with pd.option_context('display.colheader_justify','right'):
print(df_transpose['final'].to_string(index=False,header=False))

您的答案不包含列表值中所有字符串的长度。此外,最长字符串的长度应作为rjust的宽度值。

答案代码:

tableData=[["apples","oranges","cherries","banana"],
["Alice","Bob","Carol","David"],
["dogs","cat","moose","goose"]]
colWidth=[0]*len(tableData)     
def printtable(data):
colWidths = [0] * len(tableData)

for y in range(len(tableData)): #finding the length of strings in each sublist
for x in tableData[y]:
if colWidths[y] < len(x):
colWidths[y] = len(x)
width=max(colWidths) # finding the length of the longest in the list
for j in range(len(data[0])):     
for i in range(len(data)):
print(data[i][j].rjust(int(width)), end = " ")
print("n")
printtable(tableData)

希望这能有所帮助。

最新更新