为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

守候你守候我 2021-09-14 15:08:46
假设我有一个由字符串和它们出现的百分比组成的字典,如下所示:{"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?
查看完整描述

2 回答

?
守着星空守着你

TA贡献1799条经验 获得超8个赞

你需要 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


第一个参数是应该返回的值列表

第二个参数是生成传入参数的值的权重(或概率)


查看完整回答
反对 回复 2021-09-14
?
侃侃无极

TA贡献2051条经验 获得超10个赞

试试我的解决方案:


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'}



查看完整回答
反对 回复 2021-09-14
  • 2 回答
  • 0 关注
  • 226 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号