1. 程式人生 > 其它 >python程式設計快速上手-實踐專案答案5

python程式設計快速上手-實踐專案答案5

技術標籤:python程式設計快速上手課後答案python

Python程式設計快速上手第五章課後答案

好玩遊戲的物品清單

字典值:

{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

寫一個名為displayInventory()的函式,它接受任何可能的物品清單,並顯示如下:

Inventory
1 rope
6 torch
42 gold coin
1 dagger
12 arrow
Total number of items: 62

程式碼如下:

stuff = {'rope': 1, 'torch'
: 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} def displayInventory(items): print('Inventory') total_num = 0 for k, v in items.items(): print(str(v) + ' ' + k) total_num += v print('Total number of items: ' + str(total_num)) displayInventory(stuff)

列表到字典的函式,針對好玩遊戲物品清單

寫一個名為addToInventory(inventory,addedItems)的函式,其中inventory引數是一個字典,表示玩家的物品清單,addedItems引數是一個列表。
addToInventory()函式應該返回一個字典,表示更新過的物品清單。請注意,列表可以包含多個一樣的項。
輸出應如下:

Inventory
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48

程式碼如下:

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'
] def displayInventory(items): print('Inventory') total_num = 0 for k, v in items.items(): print(str(v) + ' ' + k) total_num += v print('Total number of items: ' + str(total_num)) def addToInventory(inventory, addedItem): for i in addedItem: if i in inventory: inventory[i] += 1 else: inventory[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)