python - 随机播放 python 数组中的某些项目

标签 python shuffle in-place

我需要根据第二个数组说明应该打乱哪个索引来打乱 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

最佳答案

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]

关于python - 随机播放 python 数组中的某些项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63018611/

相关文章:

python - 在 Pandas 中理解就地=真

javascript - JavaScript 中一组数字的随机排列

rust - 如何将任意就地操作应用于 &mut 引用?

python - 如何在 Python 中循环直到 EOF?

python - 使用单词列表的正则表达式

Javascript 数组随机播放

c++ - 如何使用 STL 对数组进行 k-shuffle?

python - Numpy修改数组到位?

python - 寻找最繁忙时段的算法?

python变量-跨模块不一致