【问题标题】:Python Nested Lists: Table Printer functionPython 嵌套列表:表格打印机功能
【发布时间】: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


【解决方案1】:

Python 有一个名为 zip 的内置方法,它允许我们将可迭代对象组合成一个变量。如果你将它与 pythons 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() 来证明这一点

【讨论】:

    【解决方案2】:

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

    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))
    

    【讨论】:

      【解决方案3】:

      您的答案没有包含列表值中所有长度的字符串。 最长字符串的长度也应该作为 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)
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2012-11-26
        • 1970-01-01
        • 2015-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-09
        相关资源
        最近更新 更多