在python中打印一个二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17870612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:21:58  来源:igfitidea点击:

printing a two dimensional array in python

python

提问by user2548833

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

我必须在 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

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]

回答by sihrc

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

我使用 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])

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

回答by unutbu

A combination of list comprehensionsand strjoinscan do the job:

列表推导式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]))

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-loopswith 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:

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

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

The more Pythonic cousin would be:

更 Pythonic 的表亲是:

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.

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

回答by Andrei

using indices, for loops and formatting:

使用索引、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)    

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

回答by Souradeep Nanda

There is always the easy way.

总有简单的方法。

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

回答by Ema

print(mat.__str__())

where mat is variable refering to your matrix object

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

回答by AlexP

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

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

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.array2stringis also available.

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