Python - Random sample from a range whilst avoiding certain values

别说谁变了你拦得住时间么 提交于 2020-01-03 03:02:14

问题


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.


回答1:


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)



回答2:


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).



来源:https://stackoverflow.com/questions/44349031/python-random-sample-from-a-range-whilst-avoiding-certain-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!