2020年9月21日 星期一

[ Python 常見問題 ] Printing Lists as Tabular Data

 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:
  1. teams_list = ["Man Utd""Man City""T Hotspur"]  
  2. data = np.array([[121],  
  3.                  [010],  
  4.                  [242]])  
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:
  1.            Man Utd   Man City   T Hotspur  
  2. Man Utd         1          0           0  
  3. Man City         1          1           0  
  4. Hotspur         0          1           2  
HowTo
There are some light and useful python packages for this purpose:

1. tabulate(pip install tabulate)
  1. from tabulate import tabulate  
  2. print(tabulate([['Alice'24], ['Bob'19]], headers=['Name''Age']))  
Output:
  1. Name      Age  
  2. ------  -----  
  3. Alice      24  
  4. Bob        19  
tabulate has many options to specify headers and table format.
  1. print(tabulate([['Alice'24], ['Bob'19]], headers=['Name''Age'], tablefmt='orgtbl'))  
Output:
  1. | Name   |   Age |  
  2. |--------+-------|  
  3. | Alice  |    24 |  
  4. | Bob    |    19 |  
2. PrettyTable:
  1. from prettytable import PrettyTable  
  2. t = PrettyTable(['Name''Age'])  
  3. t.add_row(['Alice'24])  
  4. t.add_row(['Bob'19])  
  5. print(t)  
Output:
  1. +-------+-----+  
  2. |  Name | Age |  
  3. +-------+-----+  
  4. | Alice |  24 |  
  5. |  Bob  |  19 |  
  6. +-------+-----+  
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:
  1. from texttable import Texttable  
  2. t = Texttable()  
  3. t.add_rows([['Name''Age'], ['Alice'24], ['Bob'19]])  
  4. print(t.draw())  
Output:
  1. +-------+-----+  
  2. | Name  | Age |  
  3. +=======+=====+  
  4. | Alice | 24  |  
  5. +-------+-----+  
  6. | Bob   | 19  |  
  7. +-------+-----+  
with texttable you can control horizontal/vertical align, border style and data types.

4. termtables:
  1. import termtables as tt  
  2.   
  3. string = tt.to_string(  
  4.     [["Alice"24], ["Bob"19]],  
  5.     header=["Name""Age"],  
  6.     style=tt.styles.ascii_thin_double,  
  7.     # alignment="ll",  
  8.     # padding=(01),  
  9. )  
  10. print(string)  
Output:
  1. +-------+-----+  
  2. | Name  | Age |  
  3. +=======+=====+  
  4. | Alice | 24  |  
  5. +-------+-----+  
  6. | Bob   | 19  |  
  7. +-------+-----+  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...