Kā Python izveidot tabulu?

Kā Python izveidot tabulu?

Šajā rakstā mēs apspriedīsim, kā Python izveidot tabulu. Python nodrošina plašu atbalstu bibliotēkām, kuras var izmantot dažādu mērķu izveidei. Šajā rakstā mēs runāsim par diviem šādiem moduļiem, kurus var izmantot, lai izveidotu tabulas.

1. metode: Izmantojot tabulu moduli

The tabulate() metode ir metode, kas atrodas tabulēt modulis, kas python programmā izveido uz tekstu balstītu tabulas izvadi, izmantojot jebkuru norādīto ievadi. To var instalēt, izmantojot tālāk norādīto komandu

pip install tabulate 

Tālāk ir sniegti daži piemēri, kas parāda, kā python izveidot tabulas:

1. piemērs

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

Izvade:

2. piemērs

Python3




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

Izvade:

2. metode: Izmantojot PrettyTable moduli

PrettyTable klase diezgan tabulas bibliotēkā tiek izmantota, lai izveidotu relāciju tabulas programmā Python. To var instalēt, izmantojot tālāk norādīto komandu.

pip install prettytable 

Piemērs:

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

Izvade:

izveidot tabulu python