我使用以下代碼縮進print
numpy 陣列的結果。
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("]")
但我認為這不是顯示結果的便捷方式。有什么辦法可以在輸出視窗中直接將整個陣列向右移動?
uj5u.com熱心網友回復:
這是一個更簡單、通用的填充函式:
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]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/485070.html
標籤:Python 麻木的 jupyter-笔记本 结盟 蟒蛇
上一篇:加快Numpy中3D矩陣的初始化