我的程序打印为
1
2
3
3
4
5
10
5
12
13
6
14
但是我要打印此形状的数组
[[[ 1 2 3]
[ 3 4 5]]
[[10 5 12]
[13 6 14]]]
# more than one dimensions
import numpy as np
a = np.array([[[1,2,3], [3,4,5]],[[10,5,12], [13,6,14]]])
print a.shape
for k in a:
for i in k:
for j in i:
print j
答案 0 :(得分:2)
In [53]: a = np.array([[[1,2,3], [3,4,5]],[[10,5,12], [13,6,14]]])
简单打印,数组的str(a)
格式:
In [54]: print(a)
[[[ 1 2 3]
[ 3 4 5]]
[[10 5 12]
[13 6 14]]]
在我看来,通过迭代来重新创建它比它值得的工作还要多。
好的,这是第一次尝试迭代:
In [66]: block = []
...: for panel in a:
...: sub = []
...: for row in panel:
...: sub.append(str(row))
...: sub = '\n'.join(sub)
...: block.append(sub)
...: block = '\n\n'.join(block)
In [67]: block
Out[67]: '[1 2 3]\n[3 4 5]\n\n[10 5 12]\n[13 6 14]'
In [68]: print(block)
[1 2 3]
[3 4 5]
[10 5 12]
[13 6 14]
答案 1 :(得分:1)
pprint
模块正是为此目的而制作的。
像这样使用:
import numpy as np
from pprint import pprint
a = np.array([[[1,2,3], [3,4,5]],[[10,5,12], [13,6,14]]])
print a.shape
pprint(a)
您将获得以下输出:
(2, 2, 3)
array([[[ 1, 2, 3],
[ 3, 4, 5]],
[[10, 5, 12],
[13, 6, 14]]])
答案 2 :(得分:-1)
您可以递归地这样做:
import numpy as np
def recursive_array_print(arr):
if isinstance(arr, (list, tuple, np.ndarray)):
print("[", end =" ")
for element in arr:
if isinstance(element, (list, tuple, np.ndarray)):
recursive_array_print(element)
else:
print(str(element), end =" ")
print("]", end =" ")
测试功能:
def separator():
print()
print("_______________")
def compare_print_and_recursive(arr):
separator()
recursive_array_print(arr)
separator()
print(arr)
separator()
#test data
testarr1=np.array([[[1,2,3], [3,4,5]],[[10,[2,3,4],12], [13,6,14]]])
testarr2=[[[1,2,3], [3,4,5]],[[10,[2,3,4],12], [13,6,14]]]
testarr3=(((1,2,3), (3,4,5)),((10,(2,3,4),12), (13,6,14)))
#printing the test data
print("np.array")
compare_print_and_recursive(testarr1)
print("list")
compare_print_and_recursive(testarr2)
print("tuple")
compare_print_and_recursive(testarr3)