Python編程快速上手實踐項目題目,歡迎指證與優化!
你在建立一個好玩的視頻遊戲。用於對玩家物品清單建模的數據結構是一個字
典。其中鍵是字符串,描述清單中的物品,值是一個整型值,說明玩家有多少該物
品。例如,字典值{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}意味着玩
家有 1 條繩索、 6 個火把、 42 枚金幣等。
寫一個名爲 displayInventory()的函數,它接受任何可能的物品清單, 並顯示以下:編程
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} def displayInventory(inventory): print("Inventory:") item_total = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) item_total += v print("Total number of items: " + str(item_total)) displayInventory(stuff)
運行結果:ruby
Inventory: 1 rope 6 torch 42 gold coin 1 dagger 12 arrow Total number of items: 62
列表到字典的函數,針對好玩遊戲物品清單
假設征服一條龍的戰利品表示爲這樣的字符串列表:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
寫一個名爲 addToInventory(inventory, addedItems)的函數, 其中 inventory 參數
是一個字典, 表示玩家的物品清單(像前面項目同樣), addedItems 參數是一個列表,
就像 dragonLoot。
addToInventory()函數應該返回一個字典, 表示更新過的物品清單。請注意, 列
表能夠包含多個一樣的項。你的代碼看起來可能像這樣:數據結構
def addToInventory(inventory, addedItems): # your code goes here inv = {'gold coin': 42, 'rope': 1} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = addToInventory(inv, dragonLoot) displayInventory(inv)
新代碼:ide
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} def displayInventory(inventory): print("Inventory:") item_total = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) item_total += v print("Total number of items: " + str(item_total)) #displayInventory(stuff) def addToInventory(inventory, addedItems): # your code goes here for i in addedItems: if i in inventory.keys(): inventory[i] += 1 else: inventory.setdefault(i,1) return inventory inv = {'gold coin': 42, 'rope': 1} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = addToInventory(inv, dragonLoot) displayInventory(inv)
運行結果:函數
Inventory: 45 gold coin 1 rope 1 dagger 1 ruby Total number of items: 48