Reputation: 105
I want to get get two different random samples from one range in python.
I tried something like this:
rd1 = random.sample(range(0, 10), 5)
rd2 = random.sample(range(0, 10), 5)
print(rd1)
print(rd2)
Output:
[2, 4, 7, 6, 8]
[2, 4, 0, 7, 5]
But i want rd1
and rd2
to have no common elements like:
[1, 3, 9, 6, 8]
[2, 4, 0, 7, 5]
or
[0, 2, 9, 6, 1]
[3, 4, 8, 7, 5]
Upvotes: 2
Views: 1057
Reputation: 32964
Get one sample of twice the length, then split it in half, something like this:
rd = random.sample(range(0, 10), 10)
rd1, rd2 = rd[:5], rd[5:]
print(rd1)
print(rd2)
Example output:
[5, 7, 1, 6, 3]
[2, 9, 4, 8, 0]
BTW you could also use random.shuffle
to get rd
:
rd = list(range(0, 10))
random.shuffle(rd)
Upvotes: 0
Reputation: 1710
random takes an iterable so generate the first list and then do a small filtering to exclude the items from the first random list :
import random
rd1 = random.sample(range(0, 10), 5)
rd2 = random.sample([i for i in range(0, 10) if i not in rd1], 5)
print(rd1)
print(rd2)
Output:
[2, 6, 9, 5, 0]
[4, 1, 3, 8, 7]
Upvotes: 3