繁体   English   中英

在python中打印一个二维数组

[英]printing a two dimensional array in python

我必须在 5x5 数组中打印此 python 代码,数组应如下所示:

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

谁能帮我打印这张表? 使用索引。

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]

列表推导式str连接的组合可以完成这项工作:

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]))

产量

   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

在 Python 中使用带有索引的for 循环通常是可以避免的,并且不被认为是“Pythonic”,因为它的可读性不如它的 Pythonic 表亲(见下文)。 但是,您可以这样做:

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

更 Pythonic 的表亲是:

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

但是,这使用了 30 个打印语句,而我的原始答案仅使用了一个。

总有简单的方法。

import numpy as np
print(np.matrix(A))

我使用 numpy 来生成数组,但列表数组的列表应该类似地工作。

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])

如果您只想打印某些索引:

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])
print(mat.__str__())

其中 mat 是指您的矩阵对象的变量

for i in A:
    print('\t'.join(map(str, i)))

使用索引、for 循环和格式:

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)    

产生输出:

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

除了简单的打印答案之外,您实际上可以通过使用numpy.set_printoptions函数来自定义打印输出。

先决条件:

>>> 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]])

以下选项:

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

结果是:

>>> 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.]]

以下选项:

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

结果是:

>>> 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  ]]


如果您只想为特定数组输出特定字符串,也可以使用函数numpy.array2string

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM