如何从python的概率列表中采样

时间:2019-07-03 08:02:56

标签: python statistics

如何从python中加起来为1的概率列表中进行采样。

例如 清单:[0.1、0.8、0.1] 第一个元素的选择时间为10%,第二个为80%,第三个为10%

1 个答案:

答案 0 :(得分:0)

使用random.choices函数允许的权重。例如:

import random

floats = [0.1, 0.8, 0.1]
weights = [0.1, 0.8, 0.1]
k = 1

choice = random.choices(population=floats, weights=weights, k=k)
print(choice)

因为它可以使k等于要选择的项目数,所以它将其作为列表返回。