Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing a two dimensional array in python

Tags:

python

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] 
like image 897
user2548833 Avatar asked Jul 25 '13 23:07

user2548833


People also ask

How do you print a two-dimensional array?

Example. public class Print2DArray { public static void main(String[] args) { final int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; for (int i = 0; i < matrix. length; i++) { //this equals to the row in our matrix. for (int j = 0; j < matrix[i].

How can I make a two-dimensional 2D array in Python?

In Python, we can access two-dimensional array elements using two indices. The first index refers to the list's indexing and the second one refers to the elements' position. If we define only one index with an array name, it returns all the elements of 2-dimensional stored in the array.

How do you print an array array in Python?

ALGORITHM: STEP 1: Declare and initialize an array. STEP 2: Loop through the array by incrementing the value of i. STEP 3: Finally, print out each element of the array.


2 Answers

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.

like image 179
unutbu Avatar answered Sep 18 '22 23:09

unutbu


There is always the easy way.

import numpy as np print(np.matrix(A)) 
like image 44
Souradeep Nanda Avatar answered Sep 22 '22 23:09

Souradeep Nanda