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

假设我有一个由字符串和它们出现的百分比组成的字典,如下所示:

{"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


守候你守候我
浏览 227回答 2
2回答

守着星空守着你

你需要 random.choicesimport randomx = {"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 randomx = {"a": 0.2, "b": 0.6, "c": 0.1, "d": 0.1}print(get_number(x))在 random.choices第一个参数是应该返回的值列表第二个参数是生成传入参数的值的权重(或概率)

侃侃无极

试试我的解决方案: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'}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python