Python 使用 tabulate 套件輸出方便閱讀的 List 和 Dictionary 資料

安裝套件:
    
pip install tabulate
    

使用示範

一般內容:
    
from tabulate import tabulate

data = [
    ["小明", 18],
    ["大頭", 20],
]

table = tabulate(data)
print(table)
    

範例輸出:
    
----  --
小明  18
大頭  20
----  --
    

表格:
    
from tabulate import tabulate

data = [
    ["小明", 18],
    ["大頭", 20],
]

table = tabulate(data, tablefmt="grid")
print(table)
    

範例輸出:
    
+------+----+
| 小明 | 18 |
+------+----+
| 大頭 | 20 |
+------+----+
    

表格也可以加上標題:
    
from tabulate import tabulate

data = [
    ["小明", 18],
    ["大頭", 20],
]

headers = ["姓名", "年齡"]
table = tabulate(data, headers=headers, tablefmt="grid")
print(table)
    

範例輸出:
    
+--------+-------+
| 姓名   |   年齡 |
+========+=======+
| 小明   |    18 |
+--------+-------+
| 大頭   |    20 |
+--------+-------+
    

文章撰寫中...請稍後...

參考資料:
pypi.org - tabulate

留言