在python中打印一个二维数组 [英] printing a two dimensional array in python
问题描述
我必须在 5x5 数组中打印此 python 代码,数组应如下所示:
0 1 4 (无穷大) 31 0 2 (无穷大) 44 2 0 1 5(inf)(inf) 1 0 33 4 5 3 0
谁能帮我打印这张表?使用索引.
for k in range(n):对于范围(n)中的我:对于范围内的 j(n):如果 A[i][k]+A[k][j]<A[i][j]:A[i][j]=A[i][k]+A[k][j]
a> 和 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])对于 A 中的行]))
收益
0 1 4 inf 31 0 2 信息 44 2 0 1 5信息 信息 1 0 33 4 5 3 0
<小时>
在 Python 中使用带有索引的 for-loops 通常是可以避免的,并且不被认为是Pythonic",因为它的可读性不如它的 Pythonic 表亲(见下文).但是,您可以这样做:
for i in range(n):对于范围内的 j(n):打印 '{:4}'.format(A[i][j]),打印
更 Pythonic 的表亲是:
对于A中的行:对于行中的 val:打印 '{:4}'.format(val),打印
然而,这使用了 30 个打印语句,而我的原始答案只使用了一个.
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]
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.
这篇关于在python中打印一个二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!