numpy之np.ndindex及np.ndenumerate

numpy中两种枚举方法
1、np.ndindex

for index in np.ndindex(3, 2, 2): print(index)

输出:
(0, 0, 0) (0, 0, 1) (0, 1, 0) (0, 1, 1) (1, 0, 0) (1, 0, 1) (1, 1, 0) (1, 1, 1) (2, 0, 0) (2, 0, 1) (2, 1, 0) (2, 1, 1)

for index in np.ndindex(Z.shape): print(index, Z[index])

(0, 0) 0 (0, 1) 1 (0, 2) 2 (1, 0) 3 (1, 1) 4 (1, 2) 5 (2, 0) 6 (2, 1) 7 (2, 2) 8

2、np.ndenumerate
Z = np.arange(9).reshape(3,3) print('Z=\n',Z) print(Z.shape) for index, value in np.ndenumerate(Z): print('1\n',index, value)

【numpy之np.ndindex及np.ndenumerate】输出:
Z= [[0 1 2] [3 4 5] [6 7 8]] (3, 3) 1 (0, 0) 0 1 (0, 1) 1 1 (0, 2) 2 1 (1, 0) 3 1 (1, 1) 4 1 (1, 2) 5 1 (2, 0) 6 1 (2, 1) 7 1 (2, 2) 8


    推荐阅读