[英]How to generate random sequence of numbers in python?
如何产生1,2,3的随机序列,条件是80%的数字将为1,15%将为2和5%将为3?
Use random
to get a random number in [0,1) and map your outputs to that interval. 使用
random
数在[0,1]中获取一个随机数,并将输出映射到该间隔。
from random import random
result = []
# Return 100 results (for instance)
for i in range(100):
res = random()
if res < 0.8:
result.append(1)
elif res < 0.95:
result.append(2)
else:
result.append(3)
return result
This is a trivial solution. 这是一个简单的解决方案。 You may want to write a more elegant one that allows you to specify the probabilities for each number in a dedicated structure (list, dict,...) rather than in a if/else statement.
您可能希望编写一个更优雅的,允许您在专用结构(列表,字典,...)中指定每个数字的概率,而不是在if / else语句中。
But then you might be better off using a dedicated library, as suggested in this answer . 但是,如本回答所示 ,您可能最好使用专用库。 Here's an example with scipy's
stats.rv_discrete
这是scipy的
stats.rv_discrete
的一个例子
from scipy import stats
xk = np.arange(1, 4)
pk = (0.8, 0.15, 0.05)
custm = stats.rv_discrete(name='custm', values=(xk, pk))
# Return 100 results (for instance)
return custm.rvs(size=100)
This should do the trick 这应该可以解决问题
import random
sequence = []
desired_length = n # how many numbers you want
for i in range(desired_length):
random_value = random.random()
if random_value < .8:
sequence.append(1)
elif random_value < .95:
sequence.append(2)
else:
sequence.append(3)
print sequence
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.