Home > Backend Development > Python Tutorial > How Can I Easily Print Lists as Tabular Data in Python?

How Can I Easily Print Lists as Tabular Data in Python?

DDD
Release: 2025-01-03 15:36:39
Original
995 people have browsed it

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"]
Copy after login

and a matrix representing table data:

data = np.array([[1, 2, 1],
                 [0, 1, 0],
                 [2, 4, 2]])
Copy after login

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
Copy after login

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']))
Copy after login

Output:

Name      Age
------  -----
Alice      24
Bob        19
Copy after login

2. PrettyTable

from prettytable import PrettyTable
t = PrettyTable(['Name', 'Age'])
t.add_row(['Alice', 24])
t.add_row(['Bob', 19])
print(t)
Copy after login

Output:

+-------+-----+
|  Name | Age |
+-------+-----+
| Alice |  24 |
|  Bob  |  19 |
+-------+-----+
Copy after login

3. texttable

from texttable import Texttable
t = Texttable()
t.add_rows([['Name', 'Age'], ['Alice', 24], ['Bob', 19]])
print(t.draw())
Copy after login

Output:

+-------+-----+
| Name  | Age |
+=======+=====+
| Alice | 24  |
+-------+-----+
| Bob   | 19  |
+-------+-----+
Copy after login
Copy after login

4. termtables

import termtables as tt

string = tt.to_string(
    [["Alice", 24], ["Bob", 19]],
    header=["Name", "Age"],
   >
Copy after login

Output:

+-------+-----+
| Name  | Age |
+=======+=====+
| Alice | 24  |
+-------+-----+
| Bob   | 19  |
+-------+-----+
Copy after login
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template