5

I want to display a simple 2D array in a tabular format with headings at the top, so that the values line up under the headings. Is there a way to do this? I have looked at pprint and printing using numpy but cannot get it to work. Here is what I have at the moment:

myArray = [['Student Name','Marks','Level'],['Johnny',68,4],['Jennifer',59,3],['William',34,2]]

for row in myArray:
    print(" ")
    for each in row:
        print(each,end = ' ')

Any suggestions?

user2127168
  • 91
  • 2
  • 11
  • ^^That code is awful IMO (But Works Well). I would use the Format parameter. Check out this website to see how padding works. Just set your padding to the largest string http://pyformat.info/ – FirebladeDan Jul 22 '15 at 15:02

1 Answers1

5

You just need to align based on the length of the longest element:

myArray = [['Student Name','Marks','Level'],['Johnny',68,4],['Jennifer',59,3],['William',34,2]]
mx = len(max((sub[0] for sub in myArray),key=len))

for row in myArray:
    print(" ".join(["{:<{mx}}".format(ele,mx=mx) for ele in row]))

Output:

Student Name Marks        Level       
Johnny       68           4           
Jennifer     59           3           
William      34           2 

To include the int values in the max length calc:

mx = max((len(str(ele)) for sub in myArray for ele in sub))
for row in myArray:
    print(" ".join(["{:<{mx}}".format(ele,mx=mx) for ele in row]))

Output:

Student Name Marks        Level       
Johnny       68           4           
Jennifer     59           3           
William      34           2       
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Thanks for this ,it's much simpler than the one I have just used from a previous answer.I'm not that familiar with these type of comprehension statements ( is that what they are called?). I can see how the print line of code works, what does max and key=len in the first line do please? – user2127168 Jul 22 '15 at 15:12
  • No prob, that did look a bit complicated. – Padraic Cunningham Jul 22 '15 at 15:13