40

I have to print this python code in a 5x5 array the array should look like this :

0 1 4 (infinity) 3
1 0 2 (infinity) 4
4 2 0 1 5
(inf)(inf) 1 0 3
3 4 5 3 0

can anyone help me print this table? using indices.

for k in range(n):
 for i in range(n):
 for j in range(n):
 if A[i][k]+A[k][j]<A[i][j]:
 A[i][j]=A[i][k]+A[k][j]
Souradeep Nanda
3,3482 gold badges35 silver badges50 bronze badges
asked Jul 25, 2013 at 23:44
4
  • Are you purposefully using j as your incrementing variable in two nested loops? Commented Jul 25, 2013 at 23:50
  • What is the mathematical formula governing the value of each item in the array? Commented Jul 25, 2013 at 23:58
  • 1
    thank you for catching my mistake. I meant ti use "i" Commented Jul 26, 2013 at 0:05
  • The triple loop has nothing to do with the question about printing a 5x5 array. It's uselessly confusing. And "can anyone help me print this table? using indices." is trivial. So answers actually answer an unformulated need, which is to have columns aligned, and not specifically using indices (a requirement explicitly added by the OP in a late edit). Commented Sep 13, 2023 at 11:11

9 Answers 9

80

There is always the easy way.

import numpy as np
print(np.matrix(A))
answered Apr 11, 2016 at 1:44
Sign up to request clarification or add additional context in comments.

7 Comments

by far the best answer, let's not reinvent the wheel
a matrix is not a wheel
This is not a good answer, if you have a matrix with a large number of float columns, it will totally mess up the display
How can I get it to print the entire matrix for one that is large, e.g. size (300, 300)?
You cant fit a 300x300 matrix on your screen anyways. Try dumping it into a CSV file. stackoverflow.com/questions/6081008/…
|
74

A combination of list comprehensions and str joins can do the job:

inf = float('inf')
A = [[0,1,4,inf,3],
 [1,0,2,inf,4],
 [4,2,0,1,5],
 [inf,inf,1,0,3],
 [3,4,5,3,0]]
print('\n'.join([''.join(['{:4}'.format(item) for item in row]) 
 for row in A]))

yields

 0 1 4 inf 3
 1 0 2 inf 4
 4 2 0 1 5
 inf inf 1 0 3
 3 4 5 3 0

Using for-loops with indices is usually avoidable in Python, and is not considered "Pythonic" because it is less readable than its Pythonic cousin (see below). However, you could do this:

for i in range(n):
 for j in range(n):
 print '{:4}'.format(A[i][j]),
 print

The more Pythonic cousin would be:

for row in A:
 for val in row:
 print '{:4}'.format(val),
 print

However, this uses 30 print statements, whereas my original answer uses just one.

answered Jul 26, 2013 at 1:05

3 Comments

I need to be able to use the given for loop. Does ANYONE know how to do this? I want to incorporate larger for loops into a program I am working on but I want to use indices.
inline joining paired with string formatting for item in iterable is so beautifully pythonic. Read as computed, the statement creates a prettily formatted string '{:4}'.format for [each]` item in` an array [row]. Those strings are placed into an array (the statement is surrounded by []), which is then the argument to ''.join. Then, each of the pretty lines are '\n'.join'ed
Note one can use generator comprehension instead of list comprehension to save 2 pairs of square brackets: print('\n'.join(''.join('{:4}'.format(item) for item in row) for row in matrix)). Also, one can use print('\n'.join(' '.join('{:3}'.format(item) for item in row) for row in matrix)) if one doesn't want the first column to be prefixed by a space.
7
for i in A:
 print('\t'.join(map(str, i)))
answered Aug 19, 2020 at 23:08

1 Comment

Best answer for arrays of arbitrary objects IMO. I think you can also make it a one-liner too like this: print('\n'.join('\t'.join(map(str, row)) for row in A))
2

I used numpy to generate the array, but list of lists array should work similarly.

import numpy as np
def printArray(args):
 print "\t".join(args)
n = 10
Array = np.zeros(shape=(n,n)).astype('int')
for row in Array:
 printArray([str(x) for x in row])

If you want to only print certain indices:

import numpy as np
def printArray(args):
 print "\t".join(args)
n = 10
Array = np.zeros(shape=(n,n)).astype('int')
i_indices = [1,2,3]
j_indices = [2,3,4]
for i in i_indices:printArray([str(Array[i][j]) for j in j_indices])
answered Jul 26, 2013 at 0:01

2 Comments

is there a way to use indices?
I'm not sure this is the best solution for this particular problem (since it doesn't specifically deal with the array structure), but you could also do something like: def print_join(*args): print "\t".join(str(arg) for arg in args). Then it would scale to any number of arguments, rather than being fixed at 5.
2
print(mat.__str__())

where mat is variable refering to your matrix object

answered Jan 31, 2018 at 11:11

1 Comment

any reason you call the private method instead of str(mat) ?
0

using indices, for loops and formatting:

import numpy as np
def printMatrix(a):
 print "Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]"
 rows = a.shape[0]
 cols = a.shape[1]
 for i in range(0,rows):
 for j in range(0,cols):
 print "%6.f" %a[i,j],
 print
 print 
def printMatrixE(a):
 print "Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]"
 rows = a.shape[0]
 cols = a.shape[1]
 for i in range(0,rows):
 for j in range(0,cols):
 print("%6.3f" %a[i,j]),
 print
 print 
inf = float('inf')
A = np.array( [[0,1.,4.,inf,3],
 [1,0,2,inf,4],
 [4,2,0,1,5],
 [inf,inf,1,0,3],
 [3,4,5,3,0]])
printMatrix(A) 
printMatrixE(A) 

which yields the output:

Matrix[5][5]
 0 1 4 inf 3
 1 0 2 inf 4
 4 2 0 1 5
 inf inf 1 0 3
 3 4 5 3 0
Matrix[5][5]
 0.000 1.000 4.000 inf 3.000
 1.000 0.000 2.000 inf 4.000
 4.000 2.000 0.000 1.000 5.000
 inf inf 1.000 0.000 3.000
 3.000 4.000 5.000 3.000 0.000
answered Mar 30, 2016 at 10:05

Comments

0

In addition to the simple print answer, you can actually customise the print output through the use of the numpy.set_printoptions function.

Prerequisites:

>>> import numpy as np
>>> inf = np.float('inf')
>>> A = np.array([[0,1,4,inf,3],[1,0,2,inf,4],[4,2,0,1,5],[inf,inf,1,0,3],[3,4,5,3,0]])

The following option:

>>> np.set_printoptions(infstr="(infinity)")

Results in:

>>> print(A)
[[ 0. 1. 4. (infinity) 3.]
 [ 1. 0. 2. (infinity) 4.]
 [ 4. 2. 0. 1. 5.]
 [(infinity) (infinity) 1. 0. 3.]
 [ 3. 4. 5. 3. 0.]]

The following option:

>>> np.set_printoptions(formatter={'float': "\t{: 0.0f}\t".format})

Results in:

>>> print(A)
[[ 0 1 4 inf 3 ]
 [ 1 0 2 inf 4 ]
 [ 4 2 0 1 5 ]
 [ inf inf 1 0 3 ]
 [ 3 4 5 3 0 ]]

If you just want to have a specific string output for a specific array, the function numpy.array2string is also available.

answered May 14, 2019 at 22:39

Comments

0

Use the function set_printoptions in NumPy.

Andreas Violaris
4,6046 gold badges22 silver badges38 bronze badges
answered May 8, 2023 at 15:22

Comments

0

For your matrix:

inf = float('inf')
A = [[0,1,4,inf,3],
 [1,0,2,inf,4],
 [4,2,0,1,5],
 [inf,inf,1,0,3],
 [3,4,5,3,0]]

Printing like this is the most straightforward way:

for row in A:
 for item in row:
 print(item, end='\t')
 print('\n')

Result:

enter image description here

answered Apr 17, 2024 at 14:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.