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