I have an array of values
d = [1,2,3,4,.....100]
I am wondering how could I create several 1-D arrays (3,20 or 100) using
random.shuffle(d)
in a single loop?
I have an array of values
d = [1,2,3,4,.....100]
I am wondering how could I create several 1-D arrays (3,20 or 100) using
random.shuffle(d)
in a single loop?
import copy, random
result = []
d = range(1, 101)
for i in xrange(100):
result.append(copy.copy(d))
random.shuffle(result[-1])
d[:] to create a shallow copy too, or use list(d). Shuffling a copy like that is comparable in speed to using sample(d); both create a copy and shuffle that copy.Use random.sample() instead, specifying a size:
sizes = (3, 20, 100)
random_lists = [random.sample(d, size) for size in sizes]
Now random_lists contains 3 randomized lists, picked from d, with 3, 20 and 100 elements respectively.
If you need a number of shuffled lists with the same length and elements as d, use random.sample() still:
random_lists = [random.sample(d, len(d)) for _ in range(3)]
Now random_lists consists of 3 lists of 100 elements, each a shuffled copy of d. From the random.sample() documentation:
Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples.