Python将任意二维数组打乱顺序
a=np.array([[6,0,2],[3,4,0],[0,0,5]])
idx, idy = np.where(a!=0)
state = np.random.get_state()
np.random.shuffle(idx)
np.random.set_state(state)
np.random.shuffle(idy)
b = np.zeros_like(a)
b[idx[:2],idy[:2]] = a[idx[:2],idy[:2]]
print(‘a:’, a)
print('b:',b)
plt.imshow(a,cmap='jet')
plt.figure()
plt.show()
plt.imshow(b,cmap='jet')
plt.figure()
plt.show()
运行结果:
a: [[6 0 2] [3 4 0] [0 0 5]]
b: [[0 0 2] [0 4 0] [0 0 0]]
(https://img-blog.csdnimg.cn/bd2bf606d28c4faa8363ddf5e38ba787.png)