如何在python中创建表格?

问题描述:

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

我要像一个表显示这一点,但我不能,除了计算一个单词和另一个单词之间的空格以使它合适之外,还有什么办法吗?

+0

你问的是GUI(图形)方面,或者使用什么数据结构? –

+0

是否要在控制台中创建表? –

+0

是在控制台中 –

您可以使用python的tabulate库来达到此目的。

例如:

>>> 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 | 
+--------+-------+-------------------+------------------+----------------+ 

使用

平板状,如上所述,或熊猫。

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) 

正如上面你提到的可以使用这样的表格库:

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 | 
+--------+-------+-------------------+------------------+----------------+