所以,我有一個想法,我可以使用一系列數字作爲字典中單個值的鍵。作爲Python中的字典鍵的範圍
我寫了下面的代碼,但我不能得到它的工作。它甚至有可能嗎?
stealth_roll = randint(1, 20)
# select from a dictionary of 4 responses using one of four ranges.
## not working.
stealth_check = {
range(1, 6) : 'You are about as stealthy as thunderstorm.',
range(6, 11) : 'You tip-toe through the crowd of walkers, while loudly calling them names.',
range(11, 16) : 'You are quiet, and deliberate, but still you smell.',
range(16, 20) : 'You move like a ninja, but attracting a handful of walkers was inevitable.'
}
print stealth_check[stealth_roll]
而不是試圖使用範圍的關鍵爲什麼不根據字典的大小滾動? – TheLazyScripter
作爲一個旁註,這樣的字典是可能的python3。由於鍵是範圍,因此您必須相應地訪問該詞典:'stealth_check [range(6,11)]'將起作用。這對你的目的來說完全沒用,只是想顯示對象模型是一致的。 – spectras
@TheLazyScripter我在整個腳本中採用了(1,20)慣例,我通常也使用隨機值作爲乘數以及場景選擇器。另外,如果這個工作,我可以對每個可能的結果應用不同的權重。 –