gpt4 book ai didi

python - 以表格形式打印字典列表

转载 作者:行者123 更新时间:2023-12-03 22:44:31 26 4
gpt4 key购买 nike

假设我将此列表作为全局列表

 dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'},
{'Major': 'Physics', 'GPA': '2.9', 'Name':'Emily'},
{'Major':'Mathematics', 'GPA': '3.5', 'Name': 'Sarah'}]

并且想要一个函数 print() 将其打印为
 name     major        GPA 
===============================
edward Biology 2.4
Emily physics 2.9
sarah mathematics 3.5

最佳答案

您可以使用模块 tabulate .
以下代码与 python 2 兼容,python 3 见注释。

>>> import tabulate
>>> dataset =[{'Major': 'Biology', 'GPA': '2.4', 'Name': 'Edward'}, {'Major': 'Physics', 'GPA': '2.9', 'Name': 'Emily'}, {'Major': 'Mathematics', 'GPA': '3.5', 'Name': 'Sarah'}]
>>> header = dataset[0].keys()
>>> rows = [x.values() for x in dataset]
>>> print tabulate.tabulate(rows, header)
Major GPA Name
----------- ----- ------
Biology 2.4 Edward
Physics 2.9 Emily
Mathematics 3.5 Sarah

您可以使用 tablefmt不同表格格式的参数
>>> print tabulate.tabulate(rows, header, tablefmt='grid')
+-------------+-------+--------+
| Major | GPA | Name |
+=============+=======+========+
| Biology | 2.4 | Edward |
+-------------+-------+--------+
| Physics | 2.9 | Emily |
+-------------+-------+--------+
| Mathematics | 3.5 | Sarah |
+-------------+-------+--------+
>>> print tabulate.tabulate(rows, header, tablefmt='rst')
=========== ===== ======
Major GPA Name
=========== ===== ======
Biology 2.4 Edward
Physics 2.9 Emily
Mathematics 3.5 Sarah
=========== ===== ======

关于python - 以表格形式打印字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40056747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com