列出游戏库存的字典功能-用Python自动化无聊的东西-chapter5

想象一下,被征服的龙的战利品被表示为这样的字符串:

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

编写一个名为的函数addToInventory(inventory, addedItems),其中inventory参数是表示玩家的库存的字典(如上一个项目中所示),addedItems参数是一个列表dragonLoot。该addToInventory()函数应该返回一个表示更新的库存的字典。请注意,该addedItems列表可以包含相同项目的倍数。你的代码看起来像这样:

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

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

#displayInventory(stuff)

'''
输出如下:
Inventory:
12 arrow
42 gold coin
1 rope
6 torch
1 dagger
Total number of items: 62
'''

def addToInventory(inventory, addedItems):
    # your code goes here
    for k,v in inventory.items():
        if addedItems in inventory:
            v=v+addedItems.get(item,0)
        else:

    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 ruby
1 dagger

Total number of items: 48

你可能感兴趣的:(Python)