每日練習三:《Python編程快速上手+讓繁瑣工做自動化》第五章實踐項目

假設征服一條龍的戰利品表示爲這樣的字符串列表:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
寫一個名爲 addToInventory(inventory, addedItems)的函數,其中 inventory 參數是一個字典,表示玩家的物品清單(像前面項目同樣),addedItems 參數是一個列表,就像 dragonLoot。addToInventory()函數應該返回一個字典,表示更新過的物品清單。ruby

 

# -*- coding:utf-8 -*-

def displayInventory(inventory):
    print('Inventory')
    total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        total += v
    print('Total number of items:' + str(total))

def addToInventory(inventory, addedItems):
    for k in addedItems:
        if k in inventory.keys():
            inventory[k] += 1
        else:
            inventory[k] = 1
    return inventory


inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
相關文章
相關標籤/搜索