Come creare una tabella in Python?

Come creare una tabella in Python?

In questo articolo discuteremo come creare una tabella in Python. Python fornisce un ampio supporto per le librerie che possono essere utilizzate per creare scopi diversi. In questo articolo parleremo di due di questi moduli che possono essere utilizzati per creare tabelle.

Metodo 1: Utilizzando il modulo Tabula

IL tabulare() metodo è un metodo presente nel file tabulare modulo che crea un output di tabella basato su testo all'interno del programma Python utilizzando qualsiasi input specificato. Può essere installato utilizzando il comando seguente

pip install tabulate 

Di seguito sono riportati alcuni esempi che descrivono come creare tabelle in Python:

Esempio 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'> ))>

Produzione:

Esempio 2

Python3




# import module> from> tabulate> import> tabulate> # assign data> mydata> => [> > [> 'a'> ,> 'b'> ,> 'c'> ],> > [> 12> ,> 34> ,> 56> ],> > [> 'Geeks'> ,> 'for'> ,> 'geeks!'> ]> ]> # display table> print> (tabulate(mydata))>

Produzione:

Metodo 2: Utilizzando il modulo PrettyTable

La classe PrettyTable all'interno della libreria Prettytable viene utilizzata per creare tabelle relazionali in Python. Può essere installato utilizzando il comando seguente.

pip install prettytable 

Esempio:

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

Produzione:

creare tabella Python