如何将 numpy 数组的后续行与第一行对齐

How to align subsequent rows of numpy array with the first row

我用以下代码缩进了 numpy 数组的 print 结果。

import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print("a[[0,1,2]]:\n","\t",a[[0,1,2]])

但只有第一行缩进,结果如下:

a[[0,1,2]]:
         [[1 2 3]
 [4 5 6]
 [7 8 9]]

我希望输出如下所示:

a[[0,1,2]]:
          [[1 2 3]
           [4 5 6]
           [7 8 9]]

我可以用下面的代码来实现效果:

print("a[[0,1,2]]:")
count = 0
indentation = "\t "
for raw in a[[0,1,2]]:
    count += 1
    if count == 1:
        print(indentation,"[", end = "")
        print(raw)
    elif count <= len(a[[0,1,2]])-1:
        print(indentation,"",raw)
    elif count == len(a[[0,1,2]]):
        print(indentation,"",raw, end="")
        print("]")

但我认为这不是显示结果的便捷方式。有没有办法直接把整个数组向右移动输出window?

这是一个更简单、通用的填充函数:

def pad(a, sep='\t'):
    from itertools import repeat
    t = repeat(sep)
    return '\n'.join(map(''.join, zip(t, str(a).split('\n'))))

print("a[[0,1,2]]:\n", pad(a[[0,1,2]]))

输出:

a[[0,1,2]]:
    [[1 2 3]
     [4 5 6]
     [7 8 9]]