我想随机交换一个一维数组中的一个0
和一个1
,这个数组只包含0和1,很多次都是N = 10^6
.这是我做一次交换的代码.
import numpy as np
# a contains only 0 and 1
a = np.array([0,1,1,0,1,1,0,0,0,1])
# j1 random position of 0, j2 random position of 1
j1 = np.random.choice(np.where(a==0)[0])
j2 = np.random.choice(np.where(a==1)[0])
# swap
a[j1], a[j2] = a[j2], a[j1]
由于我想多次执行此过程,所以在每次迭代中,我都需要使用np.where()来定位0和1的posistion,我认为这不是很有效.
Is there any other approach which can be more effecient ?