printing a two dimensional array in python

后端 未结 7 1859
执念已碎
执念已碎 2020-12-01 02:39

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            


        
相关标签:
7条回答
  • 2020-12-01 03:41

    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.

    0 讨论(0)
提交回复
热议问题