Reputation: 1407
I'm surprised I haven't found a way to do this without a loop, since it seems like a pretty standard problem.
Working in python,
I have colors = ["red","green","blue"]
and I'd like to put these elements into a list of length N in a random order. Right now I'm using:
import random
colors = ["red","green","blue"]
otherList = []
for i in range (10): # N=10
otherList.append(random.choice(colors))
This returns: otherList = ["red","green","green","green","blue","green","red","green","green","blue"]
, which is exactly what I want. I'm just looking for a more idiomatic way of doing this? Any ideas? It looked like random.sample might have been the answer, but I didn't see anything in the documentation that fit exactly my needs.
Upvotes: 3
Views: 143
Reputation: 309929
You can use a list comprehension:
[random.choice(colors) for i in range(10)] #xrange for python2 compatability
Or random.sample()
through some gymnastics:
nrandom = 10
random.sample( colors*(nrandom//len(colors)+1), nrandom )
Although I don't think that is better than the list-comprehension ...
Upvotes: 6
Reputation: 250951
>>> import random
>>> colors = ["red","green","blue"]
>>> [random.choice(colors) for i in range(10)]
['green', 'green', 'blue', 'red', 'red', 'red', 'green', 'red', 'green', 'blue']
Upvotes: 2