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
DDDOriginal
2024-12-20 07:19:09836browse

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

Output:

Name      Age
------  -----
Alice      24
Bob        19

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)

Output:

+-------+-----+
|  Name | Age |
+-------+-----+
| Alice |  24 |
|  Bob  |  19 |
+-------+-----+

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

Output:

+-------+-----+
| Name  | Age |
+=======+=====+
| Alice | 24  |
+-------+-----+
| Bob   | 19  |
+-------+-----+

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!

Statement:
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