2017-06-03 69 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列表不會太大),第二個是相反的更好(所以它不會循環太多次尋找合適的選項)。

相關問題