从元组生成随机列表,但能够选择每个项目的百分比 [英] Generating a random list from a tuple but being able to select percentage of each item
本文介绍了从元组生成随机列表,但能够选择每个项目的百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从两个项目('是','否')生成一个长度为 10000 的列表.而我 haev 的代码就是这样做的.问题是,它产生了约 50% 的肯定和 50% 的否定.如何修改此代码以便我可以设置它选择是的时间百分比.假设我想要 36.7% 的时间是肯定的.然后它应该在剩余的 63.3% 时间选择剩余的否".代码如下:
I want to generate a list of say length 10000 from two items ('yes','no'). And the code I haev does that. The problem is, it generates ~50% yes and 50% no. How can I modify this code so that I can set the percentage of time it selects yes. Suppose i want yes like 36.7% of the time. And then it should select the remaining 'no' the remaining 63.3% time. Code is below:
import random
category = ('yes','no')
length_of_field = 10000
print(length_of_field)
print(type(category))
category_attribute = [random.choice(category) for _ in range(length_of_field)]
print('\ncategory:')
print(len(category_attribute))
print(type(category_attribute))
from collections import Counter
a= Counter(category_attribute).keys()
b= Counter(category_attribute).values()
print(a,b)
推荐答案
import numpy as np
alist = np.random.choice(["No","Yes"], 1000, p=[0.633, 0.367])
内置
import random
alist = random.choices(["no", "yes"], weights=[0.633, 0.367], k=1000)
或
def generate_some_dist(p, n):
'''
p: 0~1, proba to generate yes
n: size
'''
a = []
for i in range(n):
if random.random() <= p:
a.append("yes")
else:
a.append("no")
return a
a = generate_some_dist(.367, 10000)
或
p = 0.367
n = 1000
a = ["yes" if random.random() <= p else "No" for _ in range(n) ]
这篇关于从元组生成随机列表,但能够选择每个项目的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文