Home >Backend Development >Python Tutorial >How Can I Easily Print Lists as Tabular Data in Python?
Printing Lists as Tabular Data
For beginners in Python, formatting data for tabular output can be a challenge. To illustrate this issue, let's consider a list for headings:
teams_list = ["Man Utd", "Man City", "T Hotspur"]
and a matrix representing table data:
data = np.array([[1, 2, 1], [0, 1, 0], [2, 4, 2]])
The desired tabular representation is:
Man Utd Man City T Hotspur ------- ------- ------- Man Utd 1 0 0 Man City 1 1 0 T Hotspur 0 1 2
Python Packages for Tabular Data
To simplify this process, consider using one of the following Python packages:
1. tabulate
from tabulate import tabulate print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age']))
Output:
Name Age ------ ----- Alice 24 Bob 19
2. PrettyTable
from prettytable import PrettyTable t = PrettyTable(['Name', 'Age']) t.add_row(['Alice', 24]) t.add_row(['Bob', 19]) print(t)
Output:
+-------+-----+ | Name | Age | +-------+-----+ | Alice | 24 | | Bob | 19 | +-------+-----+
3. texttable
from texttable import Texttable t = Texttable() t.add_rows([['Name', 'Age'], ['Alice', 24], ['Bob', 19]]) print(t.draw())
Output:
+-------+-----+ | Name | Age | +=======+=====+ | Alice | 24 | +-------+-----+ | Bob | 19 | +-------+-----+
4. termtables
import termtables as tt string = tt.to_string( [["Alice", 24], ["Bob", 19]], header=["Name", "Age"], >
Output:
+-------+-----+ | Name | Age | +=======+=====+ | Alice | 24 | +-------+-----+ | Bob | 19 | +-------+-----+
These packages provide various options for customizing headers, table formats, and data alignment.
The above is the detailed content of How Can I Easily Print Lists as Tabular Data in Python?. For more information, please follow other related articles on the PHP Chinese website!