【发布时间】:2021-02-23 09:52:04
【问题描述】:
我对此很陌生,我正在努力自学。正如我在标题中所说,我正在尝试创建一个包含 100 个数字的列表,这些数字的元素有 50% 的可能性是 0,或者有 50% 的变化是 0 到 1 之间的数字。我把它做成了下面的那个。它可以工作,但它是一个非常乏味且编码不好的程序。任何提示如何使它变得更好?
import random
import numpy as np
#define a list of 100 random numbers between 0 and 1
randomlist = []
for i in range(0,100):
n = random.uniform(0,1)
randomlist.append(n)
print(randomlist)
#create a list of 100 numbers of 0's and 1's
def random_binary_string(length):
sample_values = '01' # pool of strings
result_str = ''.join((random.choice(sample_values) for i in range(length)))
return (result_str)
l=100
x=random_binary_string(l)
x1=np.array(list(map(int, x)))
print(x1)
#combine both lists. Keep value if of the binary list if it is equal to zero. Else, substitute it by the value of randomlist
#corresponding to the index position
finalist=[]
for i in range(len(x1)):
if x1[i]==0:
finalist.append(x1[i])
else:
finalist.append(randomlist[i])
print(finalist)
非常感谢!
【问题讨论】:
-
MCMC会有所帮助。
标签: python list random generate