I have a list of objects 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 the
For one-liners, userandom.sample(list_to_be_shuffled, length_of_the_list)
with an example:
import random
random.sample(list(range(10)), 10)
outputs: [2, 9, 7, 8, 3, 0, 4, 1, 6, 5]
#!/usr/bin/python3
import random
s=list(range(5))
random.shuffle(s) # << shuffle before print or assignment
print(s)
# print: [2, 4, 1, 3, 0]
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.
It works fine. I am trying it here with functions as list objects:
from random import shuffle
def foo1():
print "foo1",
def foo2():
print "foo2",
def foo3():
print "foo3",
A=[foo1,foo2,foo3]
for x in A:
x()
print "\r"
shuffle(A)
for y in A:
y()
It prints out: foo1 foo2 foo3 foo2 foo3 foo1 (the foos in the last row have a random order)
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1.foo,a2.foo]
random.shuffle(b)