Python-从一个范围中随机采样,同时避免某些值
我一直在阅读Python-从一个范围中随机采样,同时避免某些值,python,random,Python,Random,我一直在阅读random模块中的random.sample()函数,但没有看到任何解决我问题的方法 我知道使用random.sample(范围(1100),5)将从“总体”中得到5个唯一的样本 我想得到一个范围(0999)内的随机数。我可以使用random.sample(范围(0999),1)但是为什么我要考虑使用random.sample() 我需要该范围内的随机数与单独数组中的任何数字都不匹配(例如,[44312738]) 有没有一个相对简单的方法可以做到这一点 另外,我对python非常陌
random
模块中的random.sample()
函数,但没有看到任何解决我问题的方法
我知道使用random.sample(范围(1100),5)
将从“总体”中得到5个唯一的样本
我想得到一个范围(0999)内的随机数。我可以使用random.sample(范围(0999),1)
但是为什么我要考虑使用random.sample()
我需要该范围内的随机数与单独数组中的任何数字都不匹配(例如,[44312738]
)
有没有一个相对简单的方法可以做到这一点
另外,我对python非常陌生,而且绝对是一个初学者——如果您想让我用我可能错过的任何信息更新问题,我会的
编辑:
意外地说了一次
random.range()
。哎哟。实现这一点的一种方法是,只需检查数字,然后将其添加到列表中,然后在列表中使用数字
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)
随机导入
非匹配=[443122738]
匹配=[]
而len(match)<6:#其中6可以替换为您想要减去1的数字
x=随机样本(范围(0999),1)
如果x不在非匹配中:
match.append(x)
主要有两种方式:
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
用法示例:
for method in method1, method2:
for i in range(10):
print(method(1, 5, [2, 4]))
print('----')
输出:
1
1
5
3
1
1
3
5
5
1
----
5
3
5
1
5
3
5
3
1
3
----
第一种方法适用于较小的范围或较大的列表
exclude
(因此选项
列表不会太大),第二种方法适用于相反的范围(因此它不会循环太多次以寻找合适的选项)。没有random.range
。你是在考虑randint吗?另外,您是想得到一个随机数,还是几个不同的随机数?@AlexHall感谢您发现错误,但match
可能有0到5个数字。@AlexHall答对了。我更新了我的答案,改为使用while循环,直到它达到所需的数量。非常感谢,这正是我需要看到的东西。