《Python编程快速上手》实践项目第五章

5.6.2 列表到字典的函数,针对好玩游戏物品清单

假设征服一条龙的战利品表示为这样的字符串列表:

dragonLoot = ['gold coin', 'dagger', 'goldcoin', 'gold coin', 'ruby']

写一个名为addToInventory(inventory,addedItems)的函数,其中inventory参数是一个字典,表示玩家的物品清单(像前面项目一样),addedItems参数是一个列表,就像dragonLoot


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

def addToInventory(inventory,addedItems):
    # your code goes here
    for i in addedItems:
        inventory.setdefault(i,0)
        inventory[i]=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)
 

你可能感兴趣的:(课后习题)