它適用于我的游戲:
import random
ships = {
"transporter": {
"type": "transporter", "price": 5000
},
"scout": {
"type": "fighter", "price": 8000
},
"interceptor": {
"type": "fighter", "price": 100003
}
}
player_ship = random.choice(list(ships))
print(player_ship)
是否可以使用輸入讀取 key: value ?例如
player_ship = input("Choose a ship:")
當用戶進入時"1"他會選擇"transporter"?
感謝您的建議。我覺得有點開竅了!:) 我還找到了一個很好的來源:https ://www.pythonpool.com/dictionary-to-list-python/ 祝大家平安!
uj5u.com熱心網友回復:
對的,這是可能的:
userInput = int(input("Choose a ship: "))
print(ships[list(ships)[userInput-1]])
示例輸出 #1
Choose a ship: 1
{'type': 'transporter', 'price': 5000}
示例輸出 #2
Choose a ship: 2
{'type': 'fighter', 'price': 8000}
請注意,您必須ships事先定義。
uj5u.com熱心網友回復:
使用當前結構,您必須按照@Amirhossein 的建議進行操作。但是,這需要為密鑰保留另一個串列。
如果你只打算ships用于這個目的,你可以這樣寫ships:
ships = [{"name": "transporter", "type": "transporter", "price": 5000},
{"name": "scout", "type": "fighter", "price": 8000},
{"name": "interceptor", "type": "fighter", "price": 100003}]
然后:
userInput = int(input("Choose a ship: "))
print(ships[userInput - 1]['name'])
現在您可以通過索引輕松訪問串列容器。
uj5u.com熱心網友回復:
嘗試這個
user_ship = int(input("Choose a ship:"))
list_of_ships = list(ships)
print(list_of_ships[user_ship - 1])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/447811.html
