Home > Backend Development > Python Tutorial > How Can I Efficiently Format Data into a Tabular Output in Python?

How Can I Efficiently Format Data into a Tabular Output in Python?

DDD
Release: 2024-12-20 07:19:09
Original
754 people have browsed it

How Can I Efficiently Format Data into a Tabular Output in Python?

Printing Data as Tabular Data

You encounter challenges in formatting data for tabular output in Python. You have a list of headings and a matrix containing the table data.

Specifically, you want to present the data as follows:




Man Utd
Man City
T Hotspur




Man Utd
1
0
0


Man City
1
1
0


T Hotspur
0
1
2


Solution

Python offers several options for elegantly solving this task:

1. tabulate (https://pypi.python.org/pypi/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 (https://pypi.python.org/pypi/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 (https://pypi.python.org/pypi/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

The above is the detailed content of How Can I Efficiently Format Data into a Tabular Output in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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