洗牌;“耦合”;python数组中的元素

洗牌;“耦合”;python数组中的元素,python,arrays,Python,Arrays,假设我有一个数组: np.arange(9) [0 1 2 3 4 5 6 7 8] 我想用np.random.shuffle对元素进行洗牌,但某些数字必须按原始顺序 我希望0,1,2有原始顺序。 我要3,4,5有原始订单。 我要6,7,8有原始顺序 数组中的元素数将是3的倍数 例如,一些可能的输出是: [ 3 4 5 0 1 2 6 7 8] [ 0 1 2 6 7 8 3 4 5] 但是这个: [2 1 0 3 4 5 6 7 8] 将无效,因为0、1、2不符合原始顺序 我认为zip

假设我有一个数组:

np.arange(9)

[0 1 2 3 4 5 6 7 8]
我想用np.random.shuffle对元素进行洗牌,但某些数字必须按原始顺序

我希望0,1,2有原始顺序。 我要3,4,5有原始订单。 我要6,7,8有原始顺序

数组中的元素数将是3的倍数

例如,一些可能的输出是:

[ 3 4 5 0 1 2 6 7 8]
[ 0 1 2 6 7 8 3 4 5]
但是这个:

[2 1 0 3 4 5 6 7 8]
将无效,因为0、1、2不符合原始顺序

我认为
zip()
在这里可能有用,但我不确定。

天真的方法:

num_indices = len(array_to_shuffle) // 3 # use normal / in python 2
indices = np.arange(num_indices)
np.random.shuffle(indices)

shuffled_array = np.empty_like(array_to_shuffle)
cur_idx = 0
for idx in indices:
   shuffled_array[cur_idx:cur_idx+3] = array_to_shuffle[idx*3:(idx+1)*3]
   cur_idx += 3
更快(更清洁)选项:


使用
numpy.random.shuffle
numpy.ndarray.flant
函数的简短解决方案:

arr = np.arange(9)
arr_reshaped = arr.reshape((3,3))   # reshaping the input array to size 3x3
np.random.shuffle(arr_reshaped)
result = arr_reshaped.flatten()

print(result)
可能的随机结果之一:

[3 4 5 0 1 2 6 7 8]

这不是编程问题,您可以添加问题。
[3 4 5 0 1 2 6 7 8]