【问题标题】:Python format tabular output [duplicate]Python格式表格输出[重复]
【发布时间】:2012-01-11 11:49:23
【问题描述】:

使用python2.7,我正在尝试打印到屏幕表格数据。

这大概是我的代码的样子:

for i in mylist:
   print "{}\t|{}\t|".format (i, f(i))

问题在于,根据if(i) 的长度,数据不会对齐。

这就是我得到的:

|foo |bar |
|foobo   |foobar  |

我想得到什么:

|foo     |bar     |
|foobo   |foobar  |

有没有允许这样做的模块?

【问题讨论】:

    标签: python


    【解决方案1】:

    滚动你自己的格式化函数并不难:

    def print_table(table):
        col_width = [max(len(x) for x in col) for col in zip(*table)]
        for line in table:
            print "| " + " | ".join("{:{}}".format(x, col_width[i])
                                    for i, x in enumerate(line)) + " |"
    
    table = [(str(x), str(f(x))) for x in mylist]
    print_table(table)
    

    【讨论】:

    • 供其他人参考,我不得不将格式字符串更改为“{0:{1}}”以使其正常工作。
    • Pylint 抱怨 * :(。它说“使用 * 或 ** 魔法”。
    • 请注意,如果表中的可迭代对象包含任何非字符串对象,则此代码可能无法正确执行,因为 len 要么未定义,要么可能不正确。要解决此问题,请将 max(len(x) 更改为 max(len(str(x))
    • 不是很难,但肯定是丑陋和不必要的。
    【解决方案2】:

    在 pypi 中有一个很好的模块,PrettyTable。

    http://code.google.com/p/prettytable/wiki/Tutorial

    http://pypi.python.org/pypi/PrettyTable/

    $ pip install PrettyTable
    

    【讨论】:

      【解决方案3】:

      为了更漂亮的表格使用表格模块:

      Tabulate link

      这里报一个例子:

      >>> from tabulate import tabulate
      
      >>> table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
      ...          ["Moon",1737,73.5],["Mars",3390,641.85]]
      >>> print tabulate(table)
      -----  ------  -------------
      Sun    696000     1.9891e+09
      Earth    6371  5973.6
      Moon     1737    73.5
      Mars     3390   641.85
      -----  ------  -------------
      

      【讨论】:

      • 是的,我用过这个,而且很简单,只需几行代码就可以拥有一个类似表格的结构!
      【解决方案4】:

      你可以试试BeautifulTable。 这是一个例子:

      >>> from beautifultable import BeautifulTable
      >>> table = BeautifulTable()
      >>> table.column_headers = ["name", "rank", "gender"]
      >>> table.append_row(["Jacob", 1, "boy"])
      >>> table.append_row(["Isabella", 1, "girl"])
      >>> table.append_row(["Ethan", 2, "boy"])
      >>> table.append_row(["Sophia", 2, "girl"])
      >>> table.append_row(["Michael", 3, "boy"])
      >>> print(table)
      +----------+------+--------+
      |   name   | rank | gender |
      +----------+------+--------+
      |  Jacob   |  1   |  boy   |
      +----------+------+--------+
      | Isabella |  1   |  girl  |
      +----------+------+--------+
      |  Ethan   |  2   |  boy   |
      +----------+------+--------+
      |  Sophia  |  2   |  girl  |
      +----------+------+--------+
      | Michael  |  3   |  boy   |
      +----------+------+--------+
      

      【讨论】:

        【解决方案5】:
        mylist = {"foo":"bar", "foobo":"foobar"}
        
        width_col1 = max([len(x) for x in mylist.keys()])
        width_col2 = max([len(x) for x in mylist.values()])
        
        def f(ind):
            return mylist[ind]
        
        for i in mylist:
            print "|{0:<{col1}}|{1:<{col2}}|".format(i,f(i),col1=width_col1,
                                                    col2=width_col2)
        

        【讨论】:

        • 它的工作原理谢谢。但令我惊讶的是,没有本地模块可以做到这一点!
        【解决方案6】:

        您似乎希望您的列左对齐,但我没有看到任何提到ljust 字符串方法的答案,所以我将在 Python 2.7 中演示:

        def bar(item):
            return item.replace('foo','bar')
        
        width = 20
        mylist = ['foo1','foo200000','foo33','foo444']
        
        for item in mylist:
            print "{}| {}".format(item.ljust(width),bar(item).ljust(width))
        
        foo1                | bar1
        foo200000           | bar200000
        foo33               | bar33
        foo444              | bar444
        

        供您参考,运行help('abc'.ljust) 会为您提供:

        S.ljust(width[, fillchar]) -> 字符串

        看起来ljust 方法采用您指定的宽度并从中减去字符串的长度,并用那么多字符填充字符串的右侧。

        【讨论】:

          猜你喜欢
          • 2017-09-14
          • 1970-01-01
          • 1970-01-01
          • 2015-06-23
          • 1970-01-01
          • 2021-02-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多