Reputation: 11754
I have a list which I want to randomly divide into two sublists of known size, which are complements of one another. e.g., I have [1,5,6,8,9]
and I want to divide it to [1,5,9]
and [6,8]
. I care less about efficiency and just want it to work. Order does not matter.
I started with:
pop = [...] #some input
samp1 = random.sample(pop, samp1len)
samp2 = [x for x in pop if x not in samp1]
However, this solution fails with repetitive items. If pop = [0,0,0,3,5]
, and the first selection of length 3 was [0,3,5]
, I would still like samp2 to be [0,0]
, which my code currently fails to provide.
Is there some built in option in random that I missed? Can anyone offer a simple solution?
Upvotes: 4
Views: 550
Reputation: 251186
How about something like this?
Generate a list of indices and shuffle them:
>>> indices = range(len(pop))
>>> random.shuffle(indices)
Then slice the indices list and use operator.itemegetter
to get the items:
>>> from operator import itemgetter
>>> itemgetter(*indices[:3])(pop)
(0, 0, 3)
>>> itemgetter(*indices[3:])(pop)
(5, 0)
Upvotes: 4