随机排列 python 数组中的某些项目
Shuffle certain items in python array
我需要打乱 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]
数组还是列表?如果您使用的是数组,则可以这样做:
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]
我需要打乱 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]
数组还是列表?如果您使用的是数组,则可以这样做:
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]