Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Random.sample from a range with excluded values (array)

I am currently using the random.sample function to extract individuals from a population.

ex:

n = range(1,1501)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

result = random.sample(n, 500)
print(result)

in this example I draw 500 persons among 1500. So far, so good..

Now, I want to go further and launch a search with a list of exclude people.

exclude = [122,506,1100,56,76,1301]

So I want to get a list of people (1494 persons) while excluding this array (exclude)

I must confess that I am stuck on this question. Do you have an idea ?
thank you in advance!

I am learning Python language. I do a lot of exercise to train. Nevertheless I block ue on this one.

>Solution :

exclude = {122, 506, 1100, 56, 76, 1301}
result = random.sample([k for k in range(1, 1501) if k not in exclude], 500)

# check
assert set(result).isdisjoint(exclude)

Marginally faster (but a bit more convoluted for my taste):

result = random.sample(list(set(range(1, 1501)).difference(exclude)), 500)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading