比如我现在有[1,2,3,4,5,6]这个数组,
如何将该数组中随机n个数字都+1,
比如将原有数组变成[2,2,4,4,5,6],
这里面就随机到了第0第2个数加一了。
>>> import numpy as np
>>> x = np.array([1,2,3,4,5,6])
>>> r = np.random.choice(np.arange(x.size), 3, replace=False) # 从x中随机无重复地抽取3个数
>>> r # 这次选中的是0,2,4
array([0, 2, 4])
>>> x[r] += 1 # 选中的数字加1
>>> x
array([2, 2, 4, 4, 6, 6])
试试这个, 可能还有更好的办法
import numpy as np
x = [1,2,3,4,5,6]
n=4
y = n*[1]+(len(x) -n)*[0]
np.random.shuffle(y)
x_re =[x[i]+y[i] for i in range(len(x))]