¿Cómo hacer una tabla en Python?

¿Cómo hacer una tabla en Python?

En este artículo, discutiremos cómo hacer una tabla en Python. Python proporciona un amplio soporte para bibliotecas que se pueden utilizar para crear diferentes propósitos. En este artículo hablaremos sobre dos de estos módulos que se pueden utilizar para crear tablas.

Método 1: Usando el módulo Tabular

El tabular() método es un método presente en el tabular módulo que crea una salida de tabla basada en texto dentro del programa Python utilizando cualquier entrada dada. Se puede instalar usando el siguiente comando.



pip install tabulate 

A continuación se muestran algunos ejemplos que muestran cómo crear tablas en Python:

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

Producción:

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

Producción:

Método 2: Usando el módulo PrettyTable

La clase PrettyTable dentro de la biblioteca Prettytable se utiliza para crear tablas relacionales en Python. Se puede instalar usando el siguiente comando.

pip install prettytable 

Ejemplo:

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

Producción:

crear tabla python



Artículos Más Populares

Categoría

Artículos De Interés