tdammon tdammon - 6 months ago 17
Python Question

I want to randomly select items from a list and add them to another list without replacement

I'm trying to randomly select items from a list and add them to another list.

The list of elements I'm choosing from looks like this:


I want to randomly take an element from this list and add it to one of four lists until each list has the same number of elements.


I have tried using random.choice but this gives me duplicates:

def fill_lists(data):
for list in lists:
for n,i in enumerate(list):
if i=='x':
list[n]= random.choice(data)

I want my function to return a list that contains 4 lists each containing a random sample of the data list with no duplicates. I also want the first element of each list to be a value that I have already placed into the list.

import random
lists = [data[i:i+len(data)/4] for i in range(0, len(data), len(data)/4)]

Randomly pulling from your initial list will have the same effect as shuffling then pulling in order. Splitting into sublists can then be done. If you need the sublists sorted, just map sort over the list afterwards.

You can change the number of groups by altering the divisor of len(data)/4

Edit: I missed this part of your question:

heads = [1,3,5,7]
[q.insert(0,p) for p,q in zip(heads,lists)]