Source From Here
Question
I have one list that is used for three headings, and a matrix that should be the contents of the table. Like so:
Note that the heading names are not necessarily the same lengths. The data entries are all integers, though. Now, I want to represent this in a table format, something like this:
HowTo
There are some light and useful python packages for this purpose:
1. tabulate: (pip install tabulate)
Output:
tabulate has many options to specify headers and table format.
Output:
2. PrettyTable:
Output:
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:
Output:
with texttable you can control horizontal/vertical align, border style and data types.
4. termtables:
Output:
I have one list that is used for three headings, and a matrix that should be the contents of the table. Like so:
- teams_list = ["Man Utd", "Man City", "T Hotspur"]
- data = np.array([[1, 2, 1],
- [0, 1, 0],
- [2, 4, 2]])
- Man Utd Man City T Hotspur
- Man Utd 1 0 0
- Man City 1 1 0
- Hotspur 0 1 2
There are some light and useful python packages for this purpose:
1. tabulate: (pip install tabulate)
- from tabulate import tabulate
- print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age']))
- Name Age
- ------ -----
- Alice 24
- Bob 19
- print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age'], tablefmt='orgtbl'))
- | Name | Age |
- |--------+-------|
- | Alice | 24 |
- | Bob | 19 |
- from prettytable import PrettyTable
- t = PrettyTable(['Name', 'Age'])
- t.add_row(['Alice', 24])
- t.add_row(['Bob', 19])
- print(t)
- +-------+-----+
- | 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())
- +-------+-----+
- | Name | Age |
- +=======+=====+
- | Alice | 24 |
- +-------+-----+
- | Bob | 19 |
- +-------+-----+
4. termtables:
- import termtables as tt
- string = 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 |
- +-------+-----+
沒有留言:
張貼留言