我希望有人可以幫助我弄清楚為什么將字典中的專案添加到名為“庫存”的新串列的代碼不起作用。這是我收到的錯誤訊息:Traceback(最近一次呼叫最后一次):檔案“C:/filenameblahblahblah”,第 71 行,ininventory.append(rooms(current_room['item'])) TypeError: 'dict' object is不可呼叫。這是我必須為課堂創建的游戲,這是游戲中唯一不適合我的部分。我需要將“物品”添加到“庫存”串列中,然后從字典“房間”中洗掉“物品”。如果我沒有正確格式化代碼示例,我提前道歉,因為我仍在學習。提前致謝。
sample of my dictionary
rooms = {
'Cabin A': {'name': 'Cabin A', 'go starboard': 'Stern', 'item': 'Spearhead', 'item name': 'a
Spearhead'},
'Cabin B': {'name': 'Cabin B', 'go port': 'Hull', 'item': 'Spear Gun', 'item name': 'a Spear
Gun'}
}
sample of what I have so far to try to pull from dictionary to add to list:
current_room = ['Cabin A']
inventory = []
if command in get_items:
if 'item' in current_room:
inventory.append(rooms(current_room['item']))
del rooms[current_room['item']]
rooms[current_room].update
print(inventory)
else:
print('Nothing here.')
uj5u.com熱心網友回復:
這部分代碼:
if 'item' in current_room:
實際上是:
if 'item' in ['Cabin A']:
換句話說,您正在檢查字串 'item' 是否是串列 ['Cabin A'] 的一部分,而事實并非如此。
其次,部分:
rooms(current_room['item'])
不管用。rooms是字典。您不能呼叫字典rooms(),而是需要這樣做rooms['Cabin A']。因此,您可以嘗試:
rooms[current_room]['item']
在哪里 current_room='Cabin A'
以下應該作業:
inventory = []
for room in rooms:
if "item" in rooms[room]:
inventory.append(rooms[room]["item"])
rooms[room].pop("item")
print(inventory)
else:
print('Nothing here')
uj5u.com熱心網友回復:
字典應該像dict[key]獲取value. 應該像訪問串列一樣訪問串列,list[index]其中index是表示您嘗試訪問的串列值索引的整數。
注意:
inventory.append(rooms(current_room['item']))
您正在使用括號訪問rooms值。您還試圖current_room像訪問字典一樣訪問該串列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/322298.html
