前言

本文主要介绍 python 中输出表格的两种方式,即分别使用tabulateprettytable

tabulate

安装、导入

1
2
3
pip install tabulate

from tabulate import tabulate

从 list 生成表格

1
2
3
4
5
6
7
>>> table = [['First Name', 'Last Name', 'Age'], ['John', 'Smith', 39], ['Mary', 'Jane', 25], ['Jennifer', 'Doe', 28]]
>>> print(tabulate(table))
---------- --------- ---
First Name Last Name Age
John Smith 39
Mary Jane 25
Jennifer Doe 28

设定表头

1
2
3
4
5
6
>>> print(tabulate(table, headers='firstrow'))
First Name Last Name Age
------------ ----------- -----
John Smith 39
Mary Jane 25
Jennifer Doe 28

传参修改样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> print(tabulate(table, headers='firstrow', tablefmt='fancy_grid'))
╒══════════════╤═════════════╤═══════╕
│ First Name │ Last Name │ Age │
╞══════════════╪═════════════╪═══════╡
│ John │ Smith │ 39 │
├──────────────┼─────────────┼───────┤
│ Mary │ Jane │ 25 │
├──────────────┼─────────────┼───────┤
│ Jennifer │ Doe │ 28 │
╘══════════════╧═════════════╧═══════╛
>>> print(tabulate(table, headers='firstrow', tablefmt='grid'))
+--------------+-------------+-------+
| First Name | Last Name | Age |
+==============+=============+=======+
| John | Smith | 39 |
+--------------+-------------+-------+
| Mary | Jane | 25 |
+--------------+-------------+-------+
| Jennifer | Doe | 28 |
+--------------+-------------+-------+

使用 dict 生成表格

1
2
3
4
5
6
7
8
9
10
11
>>> info = {'First Name': ['John', 'Mary', 'Jennifer'], 'Last Name': ['Smith', 'Jane', 'Doe'], 'Age': [39, 25, 28]}
>>> print(tabulate(info, headers='keys', tablefmt='grid'))
+--------------+-------------+-------+
| First Name | Last Name | Age |
+==============+=============+=======+
| John | Smith | 39 |
+--------------+-------------+-------+
| Mary | Jane | 25 |
+--------------+-------------+-------+
| Jennifer | Doe | 28 |
+--------------+-------------+-------+

显示索引

1
2
3
4
5
6
7
8
9
10
>>> print(tabulate(info, headers='keys', tablefmt='grid', showindex=True))
+----+--------------+-------------+-------+
| | First Name | Last Name | Age |
+====+==============+=============+=======+
| 0 | John | Smith | 39 |
+----+--------------+-------------+-------+
| 1 | Mary | Jane | 25 |
+----+--------------+-------------+-------+
| 2 | Jennifer | Doe | 28 |
+----+--------------+-------------+-------+

prettytable

安装、导入

1
2
pip install prettytable
from prettytable import PrettyTable

1
2
3
4
tb = PrettyTable() # 生成表格对象
tb.field_names = ['Index', 0, 1, 2, 3] # 定义表头
tb.add_row(['Alice',1,2,3,4]) # 添加一行,列是 column
tb.add_row(['Bob',2,3,4,5])

参考