2017-06-03 68 views
1

我一直在阅读有关random模块中的random.sample()函数,并没有看到任何解决我的问题的东西。Python - 从一个范围的随机样本,同时避免某些值

我知道,使用random.sample(range(1,100),5)会给我从“人口” 5个独特样本...

我想在range(0,999)获得一个随机数。我可以使用random.sample(range(0,999),1)但为什么然后我想使用random.sample()

我需要的随机数在该范围不是一个单独的数组匹配任意数量(比如[443,122,738]

有一个比较简单的方法,我可以去这样做呢?

此外,我对Python非常新,绝对是一个初学者 - 如果您希望我用我可能错过的任何信息更新问题,那么我会。

编辑: 意外地说random.range()一次。哎呦。

+0

没有'random.range'。你在想'randint'吗?此外,你是否试图获得一个随机数字,或几个不同的数字? –

+0

@AlexHall感谢您的错误发现对不起 – Cheesecake

回答

2

您可以通过简单地检查号码然后将其附加到列表中,然后使用号码来完成该操作。

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) 
+0

但是'match'可能有0到5个数字。 –

+0

@AlexHall很好的捕捉。我更新了我的答案,以便使用while循环,直到它达到所需的数量。 –

+0

非常感谢,这正是我需要看到的那种东西。 – Cheesecake

2

有两种主要途径:

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(所以choices列表不会太大),第二个是相反的更好(所以它不会循环太多次寻找合适的选项)。

相关问题