我想确认一下
a = [random.choices([0,1],weights=[0.2,0.8],k=1) for i in range(0,10)]
在概率上与
做同样的事情a = random.choices([0,1],weights=[0.2,0.8],k=10)
特别是,我希望两者都能从集合 {0,1} 中进行 10 次独立抽取,0 的概率为 0.2,1 的概率为 0.8。这是对的吗?
谢谢!
最佳答案
documentation似乎表明两者在概率上是相同的,并且在运行以下实验后:
from collections import defaultdict
import pprint
import random
results1 = defaultdict(int)
results2 = defaultdict(int)
for _ in range(10000):
a = [random.choices([0,1],weights=[0.2,0.8],k=1) for i in range(0,10)]
for sublist in a:
for n in sublist:
results1[n] += 1
for _ in range(10000):
a = random.choices([0,1],weights=[0.2,0.8],k=10)
for n in a:
results2[n] += 1
print('first way 0s: {}'.format(results1[0]))
print('second way 0s: {}'.format(results2[0]))
print('first way 1s: {}'.format(results1[1]))
print('second way 1s: {}'.format(results2[1]))
我发现这两种方法的结果非常相似。
关于python - python 中的 random.choices(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58423650/