2016-12-24 40 views
1

我試圖創建1到1000之間的10,000個隨機數的列表。但是我希望80-85%的數字是相同的類別(我的意思是大約100個數字其中應該出現在隨機數列表中的80%的時間),其餘的出現在大約15-20%的時間。任何想法,如果這可以在Python/NumPy/SciPy中完成。謝謝。Python中的加權隨機數值列表

+0

你能更具體?這100個號碼是否連續放置? – martianwars

+0

不,他們可以分散,但應該在1和1000之間。 –

+0

爲什麼你需要一個特殊功能呢?只需使用'random.randint()'2次。第一次選擇100與其餘的和下次選擇其中 – martianwars

回答

1

這裏有一個方法 -

a = np.arange(1,1001) # Input array to extract numbers from 

# Select 100 random unique numbers from input array and get also store leftovers 
p1 = np.random.choice(a,size=100,replace=0) 
p2 = np.setdiff1d(a,p1) 

# Get random indices for indexing into p1 and p2 
p1_idx = np.random.randint(0,p1.size,(8000)) 
p2_idx = np.random.randint(0,p2.size,(2000)) 

# Index and concatenate and randomize their positions 
out = np.random.permutation(np.hstack((p1[p1_idx], p2[p2_idx]))) 

讓運行後的驗證 -

In [78]: np.in1d(out, p1).sum() 
Out[78]: 8000 

In [79]: np.in1d(out, p2).sum() 
Out[79]: 2000 
2

這可以很容易地完成使用1致電random.randint()選擇一個列表和另一個電話random.choice()在正確的列表上。我假設列表frequent包含100個要選擇的元素80百分比和rare包含900個元素要選擇的百分比20百分比。

import random 
a = random.randint(1,5) 
if a == 1: 
    # Case for rare numbers 
    choice = random.choice(rare) 
else: 
    # case for frequent numbers 
    choice = random.choice(frequent)