在python中打印二维数组

时间:2013-07-25 23:44:28

标签: 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]

6 个答案:

答案 0 :(得分:42)

list comprehensionsstr joins的组合可以完成这项工作:

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-loops 通常是可以避免的,并且不被认为是“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个打印语句,而我的原始答案只使用了一个。

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

使用索引,循环和格式化:

 public function getAllIdsByUserIdAndProjectIdQueryBuilder($id_user, $id_project)
{   
    $qb = $this->createQueryBuilder('element')
            ->select('element.id')
            ->innerJoin('element.project', 'project')
            ->leftJoin('project.usersShared', 'user')
            ->andWhere('project.id = :id_workspace');

    $qb->andWhere(
            $qb->expr()->orX(
                    $qb->expr()->eq('user.id', ':id_user'),
                    $qb->expr()->eq('project.visibility', ':public_visibility')
                    )
            )                
            ->setParameter(':id_user', $id_user)
            ->setParameter(':public_visibility', 'PUBLIC')
            ->setParameter(':id_project', $id_project);

    return $qb;
}

产生输出:

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)    

答案 4 :(得分:0)

print(mat.__str__())

其中mat是可变的,引用你的矩阵对象

答案 5 :(得分:0)

除了简单的打印答案,您实际上还可以使用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也可用。