我是 python 新手。我想添加一個名為 delFromInventory(inventory, deletedItems) 的函式,如果他/她想從庫存中洗掉任何專案,則 deletedItems 引數是用戶的輸入。此函式應在 displayInventory() 之前回呼。我可以知道我應該如何以及在哪里撰寫腳本嗎?
以下是我當前的代碼。
def displayInventory(inventory):
print('Inventory:')
item_total = 0
for k, v in inventory.items():
print(str(v) ' ' k)
item_total = v
print('Total Items: ' str(item_total))
def addToInventory(inventory, added_items):
for loot in addedItems:
if loot not in inv:
inv[loot] = 1
else:
inv[loot] = 1
inv = {'gold coin': 42, 'rope': 1}
addedItems = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
addToInventory(inv, addedItems)
displayInventory(inv)
uj5u.com熱心網友回復:
delFromInventory()非常相似addToInventory()。您需要檢查字典中是否存在密鑰,如果不存在,您顯然無法洗掉任何內容。如果是這樣,我們需要檢查0洗掉后計數是否為(或者如果我們要在字典中有一個計數為 0 的元素,則小于 0),如果是這種情況,我們可以從清單中洗掉該鍵,因為計數是(或已經是)0。在所有其他情況下,我們可以將計數減 1。
def displayInventory(inventory):
print('Inventory:')
item_total = 0
for k, v in inventory.items():
print(str(v) ' ' k)
item_total = v
print('Total Items: ' str(item_total))
def addToInventory(inventory, added_items):
for loot in addedItems:
if loot not in inv:
inv[loot] = 1
else:
inv[loot] = 1
def delFromInventory(inventory, items_to_remove):
for item in items_to_remove:
if item not in inventory:
print(f"Can't remove {item} from inventory as it is not in inventory")
else:
count = inventory[item]
if count - 1 <= 0:
del inventory[item]
else:
inventory[item] = count - 1
inv = {'gold coin': 42, 'rope': 1}
addedItems = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
addToInventory(inv, addedItems)
displayInventory(inv)
delFromInventory(inv, ["joystick", "dagger", "ruby", "ruby"])
displayInventory(inv)
預期輸出:
Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total Items: 48
Can't remove joystick from inventory as it is not in inventory
Can't remove ruby from inventory as it is not in inventory
Inventory:
45 gold coin
1 rope
Total Items: 46
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456027.html
上一篇:為什么我的if陳述句函式只將我的列印訊息分配給python字典中的最后一個鍵值
下一篇:使用字典的Vlookup替代方案
