根据值随机选择字典键
Choose dictionary key randomly based on value
我有一本这样的字典:{"one": 5, "two": 1, "three": 25, "four": 14}
我想从字典中选择一个与值成比例的键,即 "three" 的机会最大,然后 "four" 然后 "one" 然后 "two".我看过 this 问题,但它似乎特定于数字加起来为 1 的时间。
我真的不知道如何开始,不胜感激。
使用 random.choices 和 weights
参数:
random.choices(population, weights=None, *, cum_weights=None, k=1)
Return a k sized list of elements chosen from the population with
replacement. If the population is empty, raises IndexError.
If a weights sequence is specified, selections are made according to
the relative weights. Alternatively, if a cum_weights sequence is
given, the selections are made according to the cumulative weights
import random
d = {"one": 5, "two": 1, "three": 25, "four": 14}
keys = list(d.keys())
values = list(d.values())
random_key = random.choices(keys, weights=values)
print(random_key)
# ['three']
我有一本这样的字典:{"one": 5, "two": 1, "three": 25, "four": 14}
我想从字典中选择一个与值成比例的键,即 "three" 的机会最大,然后 "four" 然后 "one" 然后 "two".我看过 this 问题,但它似乎特定于数字加起来为 1 的时间。
我真的不知道如何开始,不胜感激。
使用 random.choices 和 weights
参数:
random.choices(population, weights=None, *, cum_weights=None, k=1)
Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.
If a weights sequence is specified, selections are made according to the relative weights. Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights
import random
d = {"one": 5, "two": 1, "three": 25, "four": 14}
keys = list(d.keys())
values = list(d.values())
random_key = random.choices(keys, weights=values)
print(random_key)
# ['three']