亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從字典中,根據百分比機會返回鍵

從字典中,根據百分比機會返回鍵

守候你守候我 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 關注
  • 256 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號