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
One can define a function called shuffled
(in the same sense of sort
vs sorted
)
def shuffled(x):
import random
y = x[:]
random.shuffle(y)
return y
x = shuffled([1, 2, 3, 4])
print x
If you happen to be using numpy already (very popular for scientific and financial applications) you can save yourself an import.
import numpy as np
np.random.shuffle(b)
print(b)
https://numpy.org/doc/stable/reference/random/generated/numpy.random.shuffle.html
you could build a function that takes a list as a parameter and returns a shuffled version of the list:
from random import *
def listshuffler(inputlist):
for i in range(len(inputlist)):
swap = randint(0,len(inputlist)-1)
temp = inputlist[swap]
inputlist[swap] = inputlist[i]
inputlist[i] = temp
return inputlist
you can either use shuffle or sample . both of which come from random module.
import random
def shuffle(arr1):
n=len(arr1)
b=random.sample(arr1,n)
return b
OR
import random
def shuffle(arr1):
random.shuffle(arr1)
return arr1
random.shuffle should work. Here's an example, where the objects are lists:
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
# print(x) gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
# of course your results will vary
Note that shuffle works in place, and returns None.
""" to shuffle random, set random= True """
def shuffle(x,random=False):
shuffled = []
ma = x
if random == True:
rando = [ma[i] for i in np.random.randint(0,len(ma),len(ma))]
return rando
if random == False:
for i in range(len(ma)):
ave = len(ma)//3
if i < ave:
shuffled.append(ma[i+ave])
else:
shuffled.append(ma[i-ave])
return shuffled