首页 > 解决方案 > 随机播放python数组中的某些项目

问题描述

我需要根据第二个数组来打乱python数组的某些元素,说明应该打乱哪些索引。最好就地。

arr = [1,2,3,4,5,6]
indeces_to_shuffle = [0,4,5]

shuffle_algorithm(arr, indeces_to_shuffle) # Need help here!

print(arr)
> 6,2,3,4,1,5

标签: pythonshufflein-place

解决方案


from random import shuffle


arr = [1,2,3,4,5,6]
indeces_to_shuffle = [0,4,5]

vals = [arr[i] for i in indeces_to_shuffle]
shuffle(indeces_to_shuffle)

for i, v  in zip(indeces_to_shuffle, vals):
    arr[i] = v

print(arr)

打印(例如):

[5, 2, 3, 4, 6, 1]

推荐阅读