Python-从范围内随机抽样,同时避免某些值 [英] Python - Random sample from a range whilst avoiding certain values
问题描述
我一直在阅读有关random
模块中的random.sample()
函数的信息,但还没有发现能解决我的问题的任何信息.
I have been reading up about the random.sample()
function in the random
module and have not seen anything that solves my problem.
我知道使用random.sample(range(1,100),5)
可以从人口"中给我5个独特的样本...
I know that using random.sample(range(1,100),5)
would give me 5 unique samples from the 'population'...
我想在range(0,999)
中获得一个随机数.我可以使用random.sample(range(0,999),1)
,但是为什么要考虑使用random.sample()
?
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()
?
我需要该范围内的随机数不匹配单独数组中的任何数字(说,[443,122,738]
)
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?
此外,我对python还是一个新手,绝对是一个初学者-如果您希望我用我可能错过的任何信息来更新问题,那么我会的.
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.
一次不小心说了random.range()
.哎呀.
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)
这篇关于Python-从范围内随机抽样,同时避免某些值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!