如何根据字典的浮点值从字典中随机选择一个键

时间:2019-04-16 14:56:48

标签: python random probability

假设我有一个字典

{'option one': 5.0, 'option two': 5.0, 'option three': 10.0}

我如何根据上述概率随机选择密钥(即选项一和二将被选择为25%。选项三将被选择为50%)

1 个答案:

答案 0 :(得分:1)

作为一个班轮:

import random

random.seed(100)
d = {'option one': 5.0, 'option two': 5.0, 'option three': 10.0}
picked = random.choices(*zip(*d.items()))[0]
print(picked)
# option one

更多细分:

import random

random.seed(100)
d = {'option one': 5.0, 'option two': 5.0, 'option three': 10.0}
# Key-value pairs in dictionary
items = d.items()
# "Transpose" items: from key-value pairs to sequence of keys and sequence of values
values, weights = zip(*items)
# Weighted choice (of one element)
picked = random.choices(values, weights)[0]
print(picked)
# option one

在Python 3.6上添加了注释random.choices(与random.choice不同,它提供了weights参数)。