Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a 2D array in a "pretty" format?

Hello so let's say I have a 2D array a = [[1,2,1,2], [3,4,5,3], [8,9,4,3]] and I would like to print this out in a grid like table. So far the code I have is:

def printArray(a):
    for row in range(len(a[0])):
        for col in range (len(a[0])):
            b = print("{:8.3f}".format(a[row][col]), end = " ")
        print(b)

When this is printed out it gives me:

  1.000    2.000    1.000    2.000 None
  3.000    4.000    5.000    3.000 None
  8.000    9.000    4.000    3.000 None

And then the error:

File "hw8pr2.py", line 17, in printArray
b = print("{:8.3f}".format(a[row][col]), end = " ")

IndexError: list index out of range

Can someone tell me why this is happening? I don't want the 'None' at the end of each row either. I want it to output:

  1.000    2.000    1.000    2.000
  3.000    4.000    5.000    3.000
  8.000    9.000    4.000    3.000
like image 797
Catury Avatar asked Oct 29 '22 17:10

Catury


1 Answers

Here is what your are using:

def printArray(a):
    for row in range(len(a[0])):
        for col in range (len(a[0])):
            b = print("{:8.3f}".format(a[row][col]), end = " ")
        print(b)

You are using two for loops with len(a[0]) but your input data isn't a square, so that can't work!

You might consider using this:

def printA(a):
    for row in a:
        for col in row:
            print("{:8.3f}".format(col), end=" ")
        print("")

That will give you this:

In [14]: a = [[1, 2, 1, 2], [3, 4, 5, 3], [8, 9, 4, 3]]

In [15]: printA(a)
   1.000    2.000    1.000    2.000 
   3.000    4.000    5.000    3.000 
   8.000    9.000    4.000    3.000 

In [16]: b = [[1, 2, 1, 2, 5], [3, 4, 7, 5, 3], [8, 2, 9, 4, 3], [2, 8, 4, 7, 6]]

In [17]: printA(b)
   1.000    2.000    1.000    2.000    5.000 
   3.000    4.000    7.000    5.000    3.000 
   8.000    2.000    9.000    4.000    3.000 
   2.000    8.000    4.000    7.000    6.000 
like image 92
Xavier C. Avatar answered Nov 15 '22 06:11

Xavier C.