如何在Python制作表格?
在本文中,我们将讨论如何在Python制作表格。 Python为可用于创建不同目的的库提供了大量支持。在本文中,我们将讨论两个可用于创建表的此类模块。
方法一:使用制表模块
tabulate()方法是存在于tabulate模块中的一种方法,它使用任何给定的输入在Python程序中创建一个基于文本的表格输出。可以使用以下命令安装
pip install tabulate
下面是一些描述如何在Python创建表的示例:
示例 1
Python3
# import module
from tabulate import tabulate
# assign data
mydata = [{"Nikhil", "Delhi"},
{"Ravi", "Kanpur"},
{"Manish", "Ahmedabad"},
{"Prince", "Bangalore"}]
# create header
head = ["Name", "City"]
# display table
print(tabulate(mydata, headers=head, tablefmt="grid"))
Python3
# import module
from tabulate import tabulate
# assign data
mydata = [{'a', 'b', 'c'},
{12, 34, 56},
{'Geeks', 'for', 'geeks!'}]
# display table
print(tabulate(mydata))
Python3
from prettytable import PrettyTable
# Specify the Column Names while initializing the Table
myTable = PrettyTable(["Student Name", "Class", "Section", "Percentage"])
# Add rows
myTable.add_row(["Leanord", "X", "B", "91.2 %"])
myTable.add_row(["Penny", "X", "C", "63.5 %"])
myTable.add_row(["Howard", "X", "A", "90.23 %"])
myTable.add_row(["Bernadette", "X", "D", "92.7 %"])
myTable.add_row(["Sheldon", "X", "A", "98.2 %"])
myTable.add_row(["Raj", "X", "B", "88.1 %"])
myTable.add_row(["Amy", "X", "B", "95.0 %"])
print(myTable)
输出:
示例 2
蟒蛇3
# import module
from tabulate import tabulate
# assign data
mydata = [{'a', 'b', 'c'},
{12, 34, 56},
{'Geeks', 'for', 'geeks!'}]
# display table
print(tabulate(mydata))
输出:
方法二:使用PrettyTable模块
Prettytable 库中的 PrettyTable 类用于在Python创建关系表。可以使用以下命令安装它。
pip install prettytable
例子:
蟒蛇3
from prettytable import PrettyTable
# Specify the Column Names while initializing the Table
myTable = PrettyTable(["Student Name", "Class", "Section", "Percentage"])
# Add rows
myTable.add_row(["Leanord", "X", "B", "91.2 %"])
myTable.add_row(["Penny", "X", "C", "63.5 %"])
myTable.add_row(["Howard", "X", "A", "90.23 %"])
myTable.add_row(["Bernadette", "X", "D", "92.7 %"])
myTable.add_row(["Sheldon", "X", "A", "98.2 %"])
myTable.add_row(["Raj", "X", "B", "88.1 %"])
myTable.add_row(["Amy", "X", "B", "95.0 %"])
print(myTable)
输出: