Home > Mobile >  Python - print an array as table with column header
Python - print an array as table with column header

Time:11-25

I have a python script which produces this output:

[(22, 8, 40.0), (23, 1, 5.0), (24, 1, 5.0), ('Friday', 2, 10.0), ('Monday', 4, 20.0), ('Thursday', 2, 10.0), ('Tuesday', 1, 5.0), ('Wednesday', 1, 5.0)]

How can I get Python to show me this in a table format with the headings : Value, Count, Percentage

Additionally, I have not managed to get sorting to work. I want it to have the highest percentage value at the top of the list descending order.

My script for the sort was # sort results sorted(rank_values_perc, key=lambda x: x[2], reverse=True)

CodePudding user response:

Use tabulate:

from tabulate import tabulate

data = [(22, 8, 40.0), (23, 1, 5.0), (24, 1, 5.0), ('Friday', 2, 10.0), ('Monday', 4, 20.0), ('Thursday', 2, 10.0), ('Tuesday', 1, 5.0), ('Wednesday', 1, 5.0)]

header = ['Value', 'Count', 'Percentage']
data = sorted(data, key=lambda x: x[2], reverse=True)
print(tabulate(data, headers=header))

You can refer to this link for more options: Printing Lists as Tabular Data

  • Related