简体   繁体   中英

Python - Random sample from a range whilst avoiding certain values

I have been reading up about the random.sample() function in the random module and have not seen anything that solves my problem.

I know that using random.sample(range(1,100),5) would give me 5 unique samples from the 'population'...

I would like to get a random number in range(0,999) . I could use random.sample(range(0,999),1) but why then am I thinking about using random.sample() ?

I need the random number in that range to not match any number in a separate array (Say, [443,122,738] )

Is there a relatively easy way I could go about doing this?

Also, I am pretty new to python and am definitely a beginner -- If you would like me to update the question with any information I may have missed then I will.

EDIT: Accidentally said random.range() once. Whoops.

One way you can accomplish that is by simply checking the number and then appending it to a list where you can then use the numbers.

import random

non_match = [443, 122, 738]
match = []

while len(match) < 6: # Where 6 can be replaced with how many numbers you want minus 1
    x = random.sample(range(0,999),1)
    if x not in non_match:
        match.append(x)

There are two main ways:

import random

def method1(lower, upper, exclude):
    choices = set(range(lower, upper + 1)) - set(exclude)
    return random.choice(list(choices))

def method2(lower, upper, exclude):
    exclude = set(exclude)
    while True:
        val = random.randint(lower, upper)
        if val not in exclude:
            return val

Example usage:

for method in method1, method2:
    for i in range(10):
        print(method(1, 5, [2, 4]))
    print('----')

Output:

1
1
5
3
1
1
3
5
5
1
----
5
3
5
1
5
3
5
3
1
3
----

The first is better for a smaller range or a larger list exclude (so the choices list won't be too big), the second is better for the opposite (so it doesn't loop too many times looking for an appropriate option).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM