Python format tabular output
本问题已经有最佳答案,请猛点这里访问。
使用python2.7,我尝试打印以筛选表格数据。
我的代码大致如下:
1 2 | for i in mylist: print"{}\t|{}\t|".format (i, f(i)) |
问题是,根据
这就是我得到的:
1 2 | |foo |bar | |foobo |foobar | |
我想得到的:
1 2 | |foo |bar | |foobo |foobar | |
有没有允许这样做的模块?
滚动自己的格式化功能并不难:
1 2 3 4 5 6 7 8 | 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) |
There is a nice module for this in pypi, PrettyTable.
http://code.google.com/p/prettytable/wiki/Tutorial
http://pypi.python.org/pypi/PrettyTable/
1 | $ pip install PrettyTable |
要获得更漂亮的桌子,请使用表格模块:
列表链接
这里报告了一个示例:
1 2 3 4 5 6 7 8 9 10 11 | >>> 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 ----- ------ ------------- |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | mylist = {"foo":"bar","foobo":"foobar <div class="suo-content">[collapse title=""]<ul><li>它起作用了,谢谢。但是我很惊讶没有模块可以本地完成这个任务!</li></ul>[/collapse]</div><hr><P>你可以试试漂亮的。下面是一个例子:</P>[cc lang="python"]>>> 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 | +----------+------+--------+ |
您似乎希望列左对齐,但我没有看到任何答案提到
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 |
为供参考,运行EDOCX1[1]可提供以下信息:
S.ljust(width[, fillchar]) -> string
看起来,