Reputation: 3
i'm new to python.
I have a list of four values.
I need to choose random values from this list 32 times.
However, I need that each value be chosen exactly 8 times.
so far I used this:
import random
my_list=['a','b','c','d']
for i in range(1,33):
selection=random.choice(my_list)
print("{} selection: {}".format(i,selection))
This works - but how do I get it to give me each value exactly 8 times?
Thanks for helping.
Upvotes: 0
Views: 132
Reputation: 471
Create copies of each element with the multiply operator and then use random.shuffle to randomise the list elements:
>>> import random
>>> timesToSelectValue=8
>>> my_list=['a','b','c','d']
>>> new_list=my_list*timesToSelectValue
>>> random.shuffle(new_list)
>>> print(new_list)
['d', 'b', 'd', 'a', 'c', 'b', 'b', 'a', 'b', 'd', 'd', 'b', 'c', 'b', 'a', 'b', 'c', 'd', 'd', 'c', 'a', 'a', 'b', 'c', 'a', 'c', 'd', 'c', 'd', 'c', 'a', 'a']
new_list
is now in a random order and contains exactly 8 of each element in my_list
:
>>> for i in my_list:
... print("count {}={}".format(i,new_list.count(i)))
...
count a=8
count b=8
count c=8
count d=8
Upvotes: 1
Reputation: 25
Write a nested for loop, in which the outer for loop runs 8 times, and the inner for loop runs 4 times for the list of numbers. then in the list remove the value each time the for loop runs.
for i in range(1,8):
my_list = ['a','b','c','d']
for j in range(1,4):
rand = randint(1,(5-j))
print(rand)
my_list.remove([rand])
this is how I would do it, may not be the most efficient method, but you get the idea.
Upvotes: 1
Reputation: 117906
You can first multiply your list 8 times
>>> result = my_list*8
Then random.shuffle
that list and str.join
it.
>>> random.shuffle(result)
>>> print(''.join(result))
aaabdddbcdbcbabadcccddabbacbaccd
Upvotes: 4
Reputation: 799
In order to ensure that each value is selected at 8 times for each element in your list you're going to need a counter for each element. You'll need to keep track of how many times each element has been selected.
Every time that choice is letter is randomly selected increment its unique counter by 1. When you run your random selection again you'll need to check if that value has been selected 8 times already. If it has toss that selection and run the random selection again. Then you'll need to check and see if its randomly returned result has been selected 8 times already.
Upvotes: 1
Reputation: 190
I would build a list with the required elements in it, then shuffle it.
import random
my_list = ['a', 'b', 'c', 'd'] * 8
random.shuffle(my_list)
Now my_list contains 32 elements in random order, with each unique element appearing eight times.
Upvotes: 7