【问题标题】:How do I print a list of strings into a table in python? [closed]如何将字符串列表打印到python中的表中? [关闭]
【发布时间】:2015-06-20 14:07:35
【问题描述】:

这是列表

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

这就是我想要的样子

苹果爱丽丝狗

橘子鲍勃猫

樱桃卡罗尔驼鹿

香蕉大卫鹅

【问题讨论】:

    标签: python string list printing


    【解决方案1】:

    转置并使用 str.join:

    print("\n".join(" ".join(t) for t in zip(*tableData)))
    

    输出:

    apples Alice dogs
    oranges Bob cats
    cherries Carol moose
    banana David goose
    

    zip(*tableData)转置数据:

    [('apples', 'Alice', 'dogs'), ('oranges', 'Bob', 'cats'), ('cherries', 'Carol', 'moose'), ('banana', 'David', 'goose')]
    

    然后我们只需将每个元组中的元素连接起来,用空格分隔,然后使用换行符作为分隔符连接结果。

    使用python3使用可以使用sep

    print(*(" ".join(t) for t in zip(*tableData)), sep="\n")
    

    【讨论】:

      【解决方案2】:

      虽然没有提供完全相同的输出,但您可能有兴趣了解csvkit 如何处理绘图表:

      https://github.com/onyxfish/csvkit/blob/master/csvkit/utilities/csvlook.py#L40

      您可以根据需要进行修改(例如,如果不需要,删除所有边框)。继续为您快速完成:

      import sys
      
      def draw_table(rows):  
          widths = []
      
          # Calculate the width of each column
          for row in rows:
              for i, v in enumerate(row):
                  try:
                      if len(v) > widths[i]:
                          widths[i] = len(v)
                  except IndexError:
                      widths.append(len(v))
      
          for i, row in enumerate(rows):
      
              for j, d in enumerate(row):
                  if d is None:
                      d = ''
                  sys.stdout.write(d.ljust(widths[j] + 1))
              sys.stdout..write('\n')
      

      然后您可以只传递您的表格数据:

      > draw_table(table_data)
      
      apples oranges cherries banana 
      Alice  Bob     Carol    David  
      dogs   cats    moose    goose  
      

      【讨论】:

        猜你喜欢
        • 2022-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-06
        • 1970-01-01
        相关资源
        最近更新 更多