打乱python数组中的某些项



我需要根据第二个数组来搅乱python数组的某些元素,该数组表示应该搅乱哪些indeces。最好在适当的位置。

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]

数组还是列表?如果你使用的是一个数组,你可以这样做:

arr[indeces_to_shuffle] = np.random.permutation(arr[indeces_to_shuffle])

结果:

array([6, 2, 3, 4, 5, 1])

如果我正确理解了你的问题,我可以建议下一个:

import random
lst = [1,2,3,4,5,6]
shuffle_index = (0,4,5)
def shuffled(lst, indexes):
for i in indexes:
swap_vars = [j for j in range(len(lst)) if j != i]
swap_pos = random.choice(swap_vars)
s1, s2 = lst[i], lst[swap_pos]
lst[i], lst[swap_pos]  = s2, s1
return lst
print(f'Original: {lst}')
print(f'Shuffled: {shuffled(lst, shuffle_index)}')

输出:

Original: [1, 2, 3, 4, 5, 6]
Shuffled: [6, 5, 3, 4, 1, 2]

相关内容

  • 没有找到相关文章

最新更新