I have a list of objects in Python and I want to shuffle them. I thought I could use the random.shuffle
method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print random.shuffle(b)
This will fail.
If you happen to be using numpy already (very popular for scientific and financial applications) you can save yourself an import.
http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html
If you have multiple lists, you might want to define the permutation (the way you shuffle the list / rearrange the items in the list) first and then apply it to all lists:
Numpy / Scipy
If your lists are numpy arrays, it is simpler:
mpu
I've created the small utility package
mpu
which has theconsistent_shuffle
function:Note that
mpu.consistent_shuffle
takes an arbitrary number of arguments. So you can also shuffle three or more lists with it.For one-liners, use
random.sample(list_to_be_shuffled, length_of_the_list)
with an example:outputs: [2, 9, 7, 8, 3, 0, 4, 1, 6, 5]
you could build a function that takes a list as a parameter and returns a shuffled version of the list:
You can go for this:
if you want to go back to two lists, you then split this long list into two.