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.
you can either use shuffle or sample . both of which come from random module.
OR
In some cases when using numpy arrays, using
random.shuffle
created duplicate data in the array.An alternative is to use
numpy.random.shuffle
. If you're working with numpy already, this is the preferred method over the genericrandom.shuffle
.numpy.random.shuffle
Example
Using
random.shuffle
:Using
numpy.random.shuffle
:One can define a function called
shuffled
(in the same sense ofsort
vssorted
)random.shuffle
should work. Here's an example, where the objects are lists:Note that shuffle works in place, and returns None.
Make sure you are not naming your source file random.py, and that there is not a file in your working directory called random.pyc.. either could cause your program to try and import your local random.py file instead of pythons random module.