How to line up columns when printing from 2d array in Python? -
this question has answer here:
- pretty print 2d python list 4 answers
i want display simple 2d array in tabular format headings @ top, values line under headings. there way this? have looked @ pprint , printing using numpy cannot work. here have @ moment:
myarray = [['student name','marks','level'],['johnny',68,4],['jennifer',59,3],['william',34,2]] row in myarray: print(" ") each in row: print(each,end = ' ')
any suggestions?
you need align based on length of longest element:
myarray = [['student name','marks','level'],['johnny',68,4],['jennifer',59,3],['william',34,2]] mx = len(max((sub[0] sub in myarray),key=len)) row in myarray: print(" ".join(["{:<{mx}}".format(ele,mx=mx) ele in row]))
output:
student name marks level johnny 68 4 jennifer 59 3 william 34 2
to include int values in max length calc:
mx = max((len(str(ele)) sub in myarray ele in sub)) row in myarray: print(" ".join(["{:<{mx}}".format(ele,mx=mx) ele in row]))
output:
student name marks level johnny 68 4 jennifer 59 3 william 34 2
Comments
Post a Comment