Python小程序练习之-实践项目:战胜龙的胜利品

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

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

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

addToInventory()函数应该返回一个字典,表示更新过的物品清单.

所有代码合起来代码如下:

def addtoinventory(inventory,addeditems):
    v=0
    z=0
    for i in addeditems:
        k=inventory.get(i,0)
        k=k+1
        inventory[i]=k
    for m,n in inventory.items():
        print(str(n)+' '+m)
        z=z+n
    print('Total number of items: '+str(z))
print ('Inventory:')
inv={'gold coin':42,'rope':1}
dragonloot=['gold coin','dagger','gold coin','gold coin','ruby']
addtoinventory(inv,dragonloot)

输出结果为:

Inventory:

45 gold coin

1 rope

1 ruby

1 dagger

total number of items:48

你可能感兴趣的:(Python)