2020年3月13日python学习笔记---列表到字典的函数,针对好玩游戏物品清

假设征服一条龙的战利品表示为这样的字符串列表:
dragonLoot = [‘gold coin’, ‘dagger’, ‘gold coin’, ‘gold coin’, ‘ruby’]
写一个名为 addToInventory(inventory, addedItems)的函数,其中 inventory 参数
是一个字典,表示玩家的物品清单(像前面项目一样),addedItems 参数是一个列表,
就像 dragonLoot。
addToInventory()函数应该返回一个字典,表示更新过的物品清单。请注意,列
表可以包含多个同样的项

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

def addToInventory(inventory, addedItems):
    kong={} 
    for k, v in inventory.items():
        kong.setdefault(k,v)
        for x in range(len(addedItems)):#循环比较列表
            name=addedItems[x]
            if name==k: #如果该物品在清单中就存入清单,并且增加数量
                kong.setdefault(name,v)
                kong[k]=kong[k]+1
            elif name in inventory.keys():
                kong.setdefault(name,inventory[name])
            else:
                kong.setdefault(name,1)    
    return kong
inv={"gold coin": 42, "rope": 2, "xiao": 2}
dragonLoot = ["gold coin", "dagger", "gold coin", "gold coin", "ruby", "xiao","rope"]
inv=addToInventory(inv, dragonLoot)
displayInventory(inv)

    

输出

Inventory: 
45 gold coin
1 dagger
1 ruby
3 xiao
3 rope
Total number of items: 53

简单点的

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

def addToInventory(inventory, addedItems): 
    for x in range(len(addedItems)):#循环比较清单
        name=addedItems[x]
        if name in inventory.keys():
            inventory[name]+=1
        else:
            inventory.setdefault(name,1)          
    return inventory
inv={"gold coin": 42, "rope": 2, "xiao": 2}
dragonLoot = ["gold coin", "dagger", "gold coin", "gold coin", "ruby", "xiao","rope"]
inv=addToInventory(inv, dragonLoot)
displayInventory(inv)

    

加油!

你可能感兴趣的:(2020年3月13日python学习笔记---列表到字典的函数,针对好玩游戏物品清)