如何在python中创建表?

时间:2016-03-01 18:48:35

标签: python

这就是我想在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

我希望将它显示为一张桌子,但我不能,除了计算一个单词和另一个单词之间的空格以使其适合之外,还有其他方法吗?

3 个答案:

答案 0 :(得分:2)

为此,您可以使用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 |
+--------+-------+-------------------+------------------+----------------+

答案 1 :(得分:0)

如上所述,使用制表或Pandas。

import pandas as pd
df = pd.DataFrame({'Name': ['Alex', 'Zia', None], 
                   'Age': [13, 12, None], 
                   'Number of games': [1, 2, None], 
                   'Favourite game': ['Chess', 'Monopoly', None], 
                   'Cost of games': [10, 25, 35]})
print(df)

答案 2 :(得分:0)

如上所述,您可以像这样使用表格式库:

from tabulate import tabulate
table=[['Alex',13,1,'Chess',10],['Zia',12,2,'Chess',25]]
headers=["Name","Age", "Number of Games","Favourite Game","Cost of Game"]
print tabulate(table, headers, tablefmt="grid")

这是你将得到的:

+--------+-------+-------------------+------------------+----------------+
| Name   |   Age |   Number of Games | Favourite Game   |   Cost of Game |
+========+=======+===================+==================+================+
| Alex   |    13 |                 1 | Chess            |             10 |
+--------+-------+-------------------+------------------+----------------+
| Zia    |    12 |                 2 | Chess            |             25 |
+--------+-------+-------------------+------------------+----------------+