Home > Software engineering >  Printing in table format in Python
Printing in table format in Python

Time:07-04

For example I have a 2D python list called matrix, and the rows of the marix is given below

['Adam', 57.6271186440678, 2.542372881355932, 0.0, 39.83050847457627]
['BAMON', 40.90909090909091, 9.090909090909092, 0.0, 50.0]
['BANESH', 72.61146496815287, 0.6369426751592356, 0.0, 26.751592356687897]
['BASA', 60.317460317460316, 4.761904761904762, 1.5873015873015872, 33.333333333333336]

I want to print the 2D matrix as table with Header(Name, High Income, Medium Income in Asia, Low Income, Extreme Income in America ) and 2 digits after decimal will be considered.

Name High Income Medium Income in Asia Low Income Extreme Income in America
Adam 57.62 2.54 0.0 39.83
Bamon 40.90 9.09 0.0 50.0

How can I print it as a table or table like structure in python.

CodePudding user response:

matrix = [
    ['Adam', 57.6271186440678, 2.542372881355932, 0.0, 39.83050847457627],
    ['BAMON', 40.90909090909091, 9.090909090909092, 0.0, 50.0],
    ['BANESH', 72.61146496815287, 0.6369426751592356, 0.0, 26.751592356687897],
    ['BASA', 60.317460317460316, 4.761904761904762, 1.5873015873015872, 33.333333333333336],
]
col_names = ['High Income', 'Medium Income in Asia', 'Low Income', 'Extreme 
Income in America']

matrix.insert(0, col_names)

for e in matrix:
    if e == matrix[0]:
        print(f'{e[0]}\t\t{e[1]}\t\t{e[2]}\t\t{e[3]}')
    else:
        print(f'{e[0]}\t\t\t{round(e[1], 2)}\t\t\t\t\t\t{round(e[2], 
        2)}\t\t\t{round(e[3], 2)}')

I think there is a better way to format the tabs in the print statements.

CodePudding user response:

I solved the situation using this package https://pypi.org/project/prettytable/

from prettytable import PrettyTable
table = PrettyTable()

table.field_names = ["Name", "Low Deviation in America", "Medium Income Percentage", "High Deviation in America", "Extreme Income"]
for row in matrix:
  if(len(row)>0):
    x.add_row(row)
print(x)

CodePudding user response:

Try this:

(Adjusted from https://www.delftstack.com/howto/python/data-in-table-format-python/)

d = [['Adam', 57.6271186440678, 2.542372881355932, 0.0, 39.83050847457627],
['BAMON', 40.90909090909091, 9.090909090909092, 0.0, 50.0], 
['BANESH', 72.61146496815287, 0.6369426751592356, 0.0, 26.751592356687897],
['BASA', 60.317460317460316, 4.761904761904762, 1.5873015873015872, 33.333333333333336]]
     
print ("{:<8} {:<15} {:<15} {:<15} {:<15} ".format('Name', 'High Income', 'Medium Income in Asia', 'Low Income', 'Extreme Income in America'))

for v in d:
    name, high_income, medium_income, low_income, extreme_income = v
    print ("{:<8} {:<15} {:<15} {:<15} {:<15}".format( name, high_income, medium_income, low_income, extreme_income))

You can specify the column widths by adjusting the numbers inside the curly braces.

Hope this helps.

  • Related