假设我有一个字典
{'option one': 5.0, 'option two': 5.0, 'option three': 10.0}
我如何根据上述概率随机选择密钥(即选项一和二将被选择为25%。选项三将被选择为50%)
答案 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
参数)。