从字典中,根据百分比返回键

2024-04-25 09:59:20 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一本由字符串组成的字典,它们出现的概率为%,就像这样:

{"a": 0.2, "b": 0.6, "c": 0.1, "d": 0.1}

如何使它返回"a" 20% of the time"b" 60% of the time"c" and "d" each 10% of the time?你知道吗


Tags: andofthe字符串字典time概率each
2条回答

尝试我的解决方案:

st = {"a": 0.2, "b": 0.6, "c": 0.1, "d": 0.1}
g = dict((x, str(int(st[x] * 100)) + "% of the time") for x in st)
print(g)

{'a': '20% of the time', 'b': '60% of the time', 'c': '10% of the time', 'd': '10% of the time'}

你需要random.choices

import random
x = {"a": 0.2, "b": 0.6, "c": 0.1, "d": 0.1}
print(random.choices(list(x.keys()), list(x.values()), k=1)[0])

编辑

要使其可重用,请编写函数:

def get_number(x):
    return random.choices(list(x.keys()), list(x.values()), k=1)[0]

import random
x = {"a": 0.2, "b": 0.6, "c": 0.1, "d": 0.1}
print(get_number(x))

random.choices

  1. 第一个参数是应该返回的值的列表
  2. 第二个参数是生成传入param的值的权重(或概率)

相关问题 更多 >