简体   繁体   English

Python-从范围中随机抽样,同时避免某些值

[英]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. 我一直在阅读有关random模块中的random.sample()函数的信息,但没有看到能解决我的问题的任何东西。

I know that using random.sample(range(1,100),5) would give me 5 unique samples from the 'population'... 我知道使用random.sample(range(1,100),5)会给我5个来自“人口”的独特样本...

I would like to get a random number in range(0,999) . 我想获得一个range(0,999)的随机数。 I could use random.sample(range(0,999),1) but why then am I thinking about using random.sample() ? 我可以使用random.sample(range(0,999),1)但是为什么我要考虑使用random.sample()呢?

I need the random number in that range to not match any number in a separate array (Say, [443,122,738] ) 我需要该范围内的随机数不匹配单独数组中的任何数字(说[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. 另外,我对python还是很陌生,而且绝对是初学者-如果您希望我用我可能错过的任何信息来更新问题,那么我会的。

EDIT: Accidentally said random.range() once. 编辑:不小心说出random.range()一次。 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). 第一个对于较小的范围或较大的列表exclude (因此choices列表不会太大),第二个对于相反的列表则更好(因此在寻找合适的选项时不会循环太多)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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