比方说,我有一个由字符串组成的字典及其出现的几率,如下所示:
{"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
?
答案 0 :(得分:0)
您需要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 :(得分:0)
尝试我的解决方案:
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'}