使用python2.7,我正在尝试打印到屏幕表格数据.
这大致是我的代码:
for i in mylist:
print "{}\t|{}\t|".format (i, f(i))
Run Code Online (Sandbox Code Playgroud)
问题是,根据长度i或f(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)
Tho*_*nan 22
在pypi中有一个很好的模块,PrettyTable.
http://code.google.com/p/prettytable/wiki/Tutorial
http://pypi.python.org/pypi/PrettyTable/
$ pip install PrettyTable
Run Code Online (Sandbox Code Playgroud)
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)
似乎您希望您的列左对齐,但我还没有看到任何提到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方法采用您指定的宽度并从中减去字符串的长度,并用那么多字符填充字符串的右侧。
您可以尝试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)
| 归档时间: |
|
| 查看次数: |
64118 次 |
| 最近记录: |