python怎么输出表格

环球青藤 2020/11/13 05:44
可以使用PrettyTable 是python中的一个第三方库,可用来生成美观的ASCII格式的表格:

PrettyTable安装(推荐学习:Python视频教程)

pip install prettytable

示例

import prettytable as pt
# tb = pt.PrettyTable( ["City name", "Area", "Population", "Annual Rainfall"])
tb = pt.PrettyTable()
tb.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
tb.add_row(["Adelaide",1295, 1158259, 600.5])
tb.add_row(["Brisbane",5905, 1857594, 1146.4])
tb.add_row(["Darwin", 112, 120900, 1714.7])
tb.add_row(["Hobart", 1357, 205556,619.5])

print(tb)

输出:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Adelaide | 1295 |  1158259   |      600.5      |
|  Brisbane | 5905 |  1857594   |      1146.4     |
|   Darwin  | 112  |   120900   |      1714.7     |
|   Hobart  | 1357 |   205556   |      619.5      |
+-----------+------+------------+-----------------+

如果没有添加表头,那么会以默认的Field+编号显示,例如:

+---------+----------+----------+------------+
| Field 1 | Field 2  | Field 3  |  Field 4   |
+---------+----------+----------+------------+

更多Python相关技术文章,请访问Python教程栏目进行学习!

以上就是小编分享的关于python怎么输出表格的详细内容希望对大家有所帮助,更多有关python教程请关注环球青藤其它相关文章!

免费直播

    精选课程 更多

    注册电脑版

    版权所有 2003-2020 广州环球青藤科技发展有限公司