[英]How to print only one item from a dictionary with a changeable variable
我試圖一次只從我的字典中打印一個鍵和值,並根據玩家當前的房間位置打印它。 到目前為止我嘗試過的每個解決方案,要么打印所有項目,所有項目 10 次(有多少項目的數量),要么不打印。 我已經在網上搜索了幾個小時,非常感謝任何幫助!
rooms = {
'Lower Deck': {'up': 'Main Deck'},
'Main Deck': {'down': 'Lower Deck', 'forward': 'Main Hallway', 'item': 'Pistol'},
'Main Hallway': {'right': 'Crew Cabins', 'back': 'Main Deck', 'forward': 'Air Lock'},
'Crew Cabins': {'back': 'Main Hallway', 'item': 'Dog tags'},
'Air Lock': {'back': 'Main Hallway', 'forward': 'Crews Lounge'},
'Crews Lounge': {'back': 'Air Lock', 'right': 'Escape pods', 'left': 'Engineering Room', 'up': 'Operation Room', 'item': 'Grenade'},
'Escape pods': {'back': 'Crews Lounge'},
'Engineering Room': {'back': 'Crews Lounge'},
'Operation Room': {'back': 'Crews Lounge', 'forward': 'Control Center'},
'Control Center': {'back': 'Operation Room'}
}
這是迄今為止我嘗試過的最好的結果
for i in rooms:
i = current_room
print('The current exit to the room are: {}'.format(rooms[i]))
# output:
The current exit to the room are: {'up': 'Main Deck'}
The current exit to the room are: {'up': 'Main Deck'}
The current exit to the room are: {'up': 'Main Deck'}
...
它會在一行中顯示項目總數。 這只是第一個問題,下一個問題我必須根據玩家所在的房間進行調整。這就是我目前讓玩家從一個房間移動到另一個房間的方法(可行):
current_room = 'Lower Deck'
command = input("Please enter your move:\n").split()
if command[0].capitalize() == 'Go':
if command[1] in directions:
room_dict = rooms[current_room]
if command[1] in room_dict:
current_room = room_dict[command[1]]
else:
print("There is no exit that direction.\n")
如果您只想打印當前房間的出口,則根本不需要遍歷rooms
。
這將打印出口和它們通往的地方:
print(rooms[current_room])
或者,如果您只想打印出口:
for exit in rooms[current_room]:
print(exit)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.