python - How to print a 2D array in a "pretty" format? -
hello let's have 2d array a = [[1,2,1,2], [3,4,5,3], [8,9,4,3]] , print out in grid table. far code have is:
def printarray(a): row in range(len(a[0])): col in range (len(a[0])): b = print("{:8.3f}".format(a[row][col]), end = " ") print(b) when printed out 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 error:
file "hw8pr2.py", line 17, in printarray b = print("{:8.3f}".format(a[row][col]), end = " ") indexerror: list index out of range can tell me why happening? don't want 'none' @ end of each row either. want 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
there 3 main issues code have posted: way of iterating through array, assignment of b variable return of print statement, , printing of b variable.
firstly, way iterating through array counter-intuitive. can use
def printarray(arr): row in arr: item in row: # code printing to make more clear.
secondly, understanding of print statement seems bit lacking. print statement takes in argument , prints out directly, there no need assign variable. since print statement has no official return, automatically returns none, ties in next point explain nones @ end of print statements.
finally, printing of b variable has value none assigned discussed above produces nones see.
to fix code, use following solution.
a = [[1,2,1,2], [3,4,5,3], [8,9,4,3]] def printarray(arr): row in arr: item in row: print("{:8.3f}".format(item), end = " ") print("") printarray(a) other things stated above, code differs adding print(""), equivalent new line, after every row in array.
Comments
Post a Comment