python - python 中的 random.choices()

标签 python random

我想确认一下

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/

相关文章:

python - 如何将 % 符号添加到我的 Python 脚本中

python - 无法停止项目源代码中的循环

c - 编程不同权重的随机分布

创建基于矢量的拼图的算法

r - 如何为每个分组元素选择随机的非连续日期?

python - 获取 POST 数据并返回 res.end() - 编码问题

python - 搜索大量文本文件python

python - 数据帧属性错误: 'Index' object has no attribute 'date'

jquery - 在一个 div 或 post 中随机更改指定元素的颜色

Java数组最小值和最大值问题