Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fix first element, shuffle the rest of a list/array

Tags:

python

shuffle

Is it possible to shuffle only a (continuous) part of a given list (or array in numpy)?

If this is not generally possible, how about the special case where the first element is fixed while the rest of the list/array need to be shuffled? For example, I have a list/array:

to_be_shuffled = [None, 'a', 'b', 'c', 'd', ...]

where the first element should always stay, while the rest are going to be shuffled repeatedly.

One possible way is to shuffle the whole list first, and then check the first element, if it is not the special fixed element (e.g. None), then swap its position with that of the special element (which would then require a lookup).

Is there any better way for doing this?

like image 853
skyork Avatar asked Jul 29 '12 02:07

skyork


People also ask

How do you shuffle elements in an array?

Shuffle Array using Random Class We can iterate through the array elements in a for loop. Then, we use the Random class to generate a random index number. Then swap the current index element with the randomly generated index element. At the end of the for loop, we will have a randomly shuffled array.

How do you shuffle data in a list?

Shuffle a List. Use the random. shuffle(list1) function to shuffle a list1 in place. As shuffle() function doesn't return anything.

How do I shuffle the order of a list in Python?

Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.


2 Answers

Why not just

import random
rest = to_be_shuffled[1:]
random.shuffle(rest)
shuffled_lst = [to_be_shuffled[0]] + rest
like image 70
David Robinson Avatar answered Sep 28 '22 08:09

David Robinson


numpy arrays don't copy data on slicing:

numpy.random.shuffle(a[1:])
like image 28
jfs Avatar answered Sep 28 '22 06:09

jfs