0

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?

2
  • 1
    Sorry, what kind of output do you expect? Different length randomized subsets from the input list, where the lengths are known up front? I think you want one list 3 with 3 random elements, one with 20 and one with 100, correct? Commented May 2, 2013 at 17:06
  • You could create an array to store the generated arrays. You would just append the newly generated array to the array holder. Commented May 2, 2013 at 17:08

2 Answers 2

1
import copy, random

result = []
d = range(1, 101)
for i in xrange(100):
    result.append(copy.copy(d))
    random.shuffle(result[-1])
Sign up to request clarification or add additional context in comments.

1 Comment

You can use 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.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.