python 安装pip
访问官网:
https://pypi.python.org/pypi/pip
下载:
安装:
tar fvxz pip-8.1.2.tar.gz && cd pip-8.1.2 && chmod +x setup.py && python setup.py install pip2.6 install tabulate
执行python:
>>> 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 ----- ------ -------------
二、把相应的字段头放到表格前端
使用headers选项
>>> print tabulate(table, headers=["Planet","sina", "baidu"]) Planet sina baidu -------- ------ ------------- Sun 696000 1.9891e+09 Earth 6371 5973.6 Moon 1737 73.5 Mars 3390 641.85
如果行表头在第一个字段则使用headers="firstrow"
如下:
>>> print tabulate([["Name","age"],["liyuanchuaun","25"],["gaolixu","25"]],headers="firstrow") Name age ------------ ----- liyuanchuaun 25 gaolixu 25
table支持的格式很多具体如下:
Supported table formats are:
“plain”
“simple”
“grid”
“fancy_grid”
“pipe”
“orgtbl”
“rst”
“mediawiki”
“html”
“latex”
“latex_booktabs”
以对每个参数做了测试,需要哪个参数可以自己选择
>>> table = [["spam",42],["eggs",455],["bacon",23]] >>> headers = ["item","qty"] >>> print tabulate(table,headers) item qty ------ ----- spam 42 eggs 455 bacon 23 >>> print tabulate(table,headers,tablefmt="plain") item qty spam 42 eggs 455 bacon 23 >>> print tabulate(table,headers,tablefmt="simple") item qty ------ ----- spam 42 eggs 455 bacon 23 >>> print tabulate(table,headers,tablefmt="grid") +--------+-------+ | item | qty | +========+=======+ | spam | 42 | +--------+-------+ | eggs | 455 | +--------+-------+ | bacon | 23 | +--------+-------+ >>> print tabulate(table,headers,tablefmt="psql") +--------+-------+ | item | qty | |--------+-------| | spam | 42 | | eggs | 455 | | bacon | 23 | +--------+-------+ >>> print tabulate(table,headers,tablefmt="rst") ====== ===== item qty ====== ===== spam 42 eggs 455 bacon 23 ====== ===== >>> print tabulate(table,headers,tablefmt="orgtbl") | item | qty | |--------+-------| | spam | 42 | | eggs | 455 | | bacon | 23 | >>> print tabulate(table,headers,tablefmt="mediawiki") {| class="wikitable" style="text-align: left;" |+ <!-- caption --> |- ! item !! align="right"| qty |- | spam || align="right"| 42 |- | eggs || align="right"| 455 |- | bacon || align="right"| 23 |} >>> print tabulate(table,headers,tablefmt="html") <table> <tr><th>item </th><th style="text-align: right;"> qty</th></tr> <tr><td>spam </td><td style="text-align: right;"> 42</td></tr> <tr><td>eggs </td><td style="text-align: right;"> 455</td></tr> <tr><td>bacon </td><td style="text-align: right;"> 23</td></tr> </table> >>> print tabulate(table,headers,tablefmt="latex") \begin{tabular}{lr} \hline item & qty \\hline spam & 42 \ eggs & 455 \ bacon & 23 \\hline \end{tabular} >>>
本文出自 “linux世界” 博客,请务必保留此出处http://liyuanchuan8.blog.51cto.com/6060290/1845136
原文:http://liyuanchuan8.blog.51cto.com/6060290/1845136