TransWikia.com

Shuffle certain items in python array

Stack Overflow Asked by David Ferris on November 10, 2021

I need to shuffle certain elements of a python array depending on a second array saying which indeces should be shuffled. Preferably in-place.

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

3 Answers

If I've understood your question correctly, I can suggest next:

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)}')

Output:

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

Answered by Archirk on November 10, 2021

Array or list? You can do this if you're using an array:

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

Result:

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

Answered by Nicolas Gervais on November 10, 2021

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)

Prints (for example):

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

Answered by Andrej Kesely on November 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP