2016-12-24 105 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)