Python格式表格输出

rah*_*hmu 24 python

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

这大致是我的代码:

for i in mylist:
   print "{}\t|{}\t|".format (i, f(i))
Run Code Online (Sandbox Code Playgroud)

问题是,根据长度if(i)数据不会对齐.

这就是我得到的:

|foo |bar |
|foobo   |foobar  |
Run Code Online (Sandbox Code Playgroud)

我想得到什么:

|foo     |bar     |
|foobo   |foobar  |
Run Code Online (Sandbox Code Playgroud)

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

Sve*_*ach 28

滚动自己的格式化功能并不是很难:

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)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果表中的iterables包含任何非字符串对象,则此代码可能无法正确执行,因为len将不会被定义,或者可能不正确.要解决这个问题,请将`max(len(x)`更改为`max(len(str(x))`. (5认同)
  • 对于其他人的参考,我不得不将格式字符串更改为"{0:{1}}"以使其正常工作. (3认同)
  • 不是很难,但肯定是丑陋和不必要的。 (2认同)

Tom*_*soF 20

对于更漂亮的表使用制表模块:

制表链接

这里报告了一个例子:

>>> 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
-----  ------  -------------
Run Code Online (Sandbox Code Playgroud)


小智 8

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)
Run Code Online (Sandbox Code Playgroud)

  • 它的工作谢谢.但我很惊讶没有模块可以原生这样做! (3认同)

fou*_*ing 7

似乎您希望您的列左对齐,但我还没有看到任何提到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
Run Code Online (Sandbox Code Playgroud)

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

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

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


Pri*_*ngh 7

您可以尝试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   |
+----------+------+--------+
Run Code Online (Sandbox Code Playgroud)