2 回答

TA貢獻1799條經(jīng)驗 獲得超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])
編輯
要使其可重用,請編寫一個函數(shù):
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
第一個參數(shù)是應(yīng)該返回的值列表
第二個參數(shù)是生成傳入?yún)?shù)的值的權(quán)重(或概率)

TA貢獻2051條經(jīng)驗 獲得超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'}
添加回答
舉報