Printing Lists as Tabular Data Printing Lists as Tabular Data python python

Printing Lists as Tabular Data


There are some light and useful python packages for this purpose:

1. tabulate: https://pypi.python.org/pypi/tabulate

from tabulate import tabulateprint(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age']))
Name      Age------  -----Alice      24Bob        19

tabulate has many options to specify headers and table format.

print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age'], tablefmt='orgtbl'))
| Name   |   Age ||--------+-------|| Alice  |    24 || Bob    |    19 |

2. PrettyTable: https://pypi.python.org/pypi/PrettyTable

from prettytable import PrettyTablet = PrettyTable(['Name', 'Age'])t.add_row(['Alice', 24])t.add_row(['Bob', 19])print(t)
+-------+-----+|  Name | Age |+-------+-----+| Alice |  24 ||  Bob  |  19 |+-------+-----+

PrettyTable has options to read data from csv, html, sql database. Also you are able to select subset of data, sort table and change table styles.

3. texttable: https://pypi.python.org/pypi/texttable

from texttable import Texttablet = Texttable()t.add_rows([['Name', 'Age'], ['Alice', 24], ['Bob', 19]])print(t.draw())
+-------+-----+| Name  | Age |+=======+=====+| Alice | 24  |+-------+-----+| Bob   | 19  |+-------+-----+

with texttable you can control horizontal/vertical align, border style and data types.

4. termtables: https://github.com/nschloe/termtables

import termtables as ttstring = tt.to_string(    [["Alice", 24], ["Bob", 19]],    header=["Name", "Age"],    style=tt.styles.ascii_thin_double,    # alignment="ll",    # padding=(0, 1),)print(string)
+-------+-----+| Name  | Age |+=======+=====+| Alice | 24  |+-------+-----+| Bob   | 19  |+-------+-----+

with texttable you can control horizontal/vertical align, border style and data types.

Other options:

  • terminaltables Easily draw tables in terminal/console applications from a list of lists of strings. Supports multi-line rows.
  • asciitable Asciitable can read and write a wide range of ASCII table formats via built-in Extension Reader Classes.


Some ad-hoc code:

row_format ="{:>15}" * (len(teams_list) + 1)print(row_format.format("", *teams_list))for team, row in zip(teams_list, data):    print(row_format.format(team, *row))

This relies on str.format() and the Format Specification Mini-Language.


>>> import pandas>>> pandas.DataFrame(data, teams_list, teams_list)           Man Utd  Man City  T HotspurMan Utd    1        2         1        Man City   0        1         0        T Hotspur  2        4         2        


matomo