Skip to main content
 首页 » 编程设计

python之如何在 python 中创建表

2024年10月24日9lhb25

这是我想在 Python 中复制的内容:

这些是存储数据的变量的名称:

name_1= "Alex" 
name_2 ="Zia" 
age_1 = 13 
age_2 = 12 
game_1= 1 
game_2 = 2 
favourite_1 ="chess" 
favourite_2 = "monopoly" 
cost_1= 10 
cost_2 =25 
total_cost = 25 

我想像表格一样显示它,但我不能,除了计算一个单词和另一个单词之间的空格以使其适合之外,还有其他方法吗?

请您参考如下方法:

您可以使用 tabulate用于此目的的 python 库。

例如:

>>> from tabulate import tabulate 
>>> value_list = [['Alex', 13,1, 'Chess', 10], 
                  ['Zia',  12,2, 'Monopoly', 25]] 
>>> column_list = ["Name", "Age", "Number of Games", "Favourite Game", "Cost of Game"] 
>>> print tabulate(value_list, column_list, tablefmt="grid") 
+--------+-------+-------------------+------------------+----------------+ 
| Name   |   Age |   Number of Games | Favourite Game   |   Cost of Game | 
+========+=======+===================+==================+================+ 
| Alex   |    13 |                 1 | Chess            |             10 | 
+--------+-------+-------------------+------------------+----------------+ 
| Zia    |    12 |                 2 | Monopoly         |             25 | 
+--------+-------+-------------------+------------------+----------------+