繁体   English   中英

使用 Python 自动化无聊的东西 - 第 5 章,奇幻游戏清单

[英]Automate the Boring Stuff with Python - Chapter 5, Fantasy Game Inventory

下面是我正在测试的代码:

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

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

displayInventory(stuff)

##
inv = {'gold coin':42, 'rope':1}
dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'}
def addToInventory(inventory, addedItems):
    for i in addedItems:
        inventory.setdefault(i, 0)
        inventory[i] += 1
    return inventory
dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'}
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

我希望它会回来

Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 46

但我只得到 43 的“金币”钥匙。 为什么是这样?

问题是,您使用的是set

dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'}
print(dragonLoot)

Output:

{'dagger', 'gold coin', 'ruby'}

一套将确保每件物品都是独一无二的,因此重复的“金币”将被丢弃。

解决方案:改用list

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

Output:

Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48

这就是我解决它的方法:

def toDisplay(inventory):
    print('Inventory: ')
    total_items = 0
    for i, j in inventory.items():
        total_items = total_items + j
        print(str(j)+ ' ' + i)
    print('Total items are: ' + str(total_items))
    

def toAdd(main_inven, addedItems):
    for i in addedItems:
        main_inven.setdefault(i, 0)
        main_inven[i] = main_inven[i] + 1
    return main_inven

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
unlocked = ['arrow', 'gold coin', 'gold coin', 'arrow', 'gold coin', 'torch', 'compass', 'ancient map']
updated_inven = toAdd(stuff, unlocked)
#print(updated_inven)
toDisplay(updated_inven)
stuff={'rope':1, 'gold coin':42}
dragonloot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

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

def addToInventory(inventory, addedItems):
    for i in addedItems:
        inventory.setdefault(i,0)
        inventory[i] +=1
    return inventory

inv= addToInventory(stuff,dragonloot)
displayInventory(inv)

我的版本将 addedItems 列表转换为字典。 它将两个字典合并到第三个字典中。 然后将两个字典的值相加,并将值存储到第三个字典中。
最后,它将第 3 个字典重命名为库存并将其返回到 displayInventory function。 它不够优雅,但仍然是解决此问题的另一种方法。

def displayInventory(inventory):
    print("Inventory:")
    item_total = 0

    for k,v in inventory.items():
        #FILL THIS PART IN
        print(str(v) + ' ' + k)
        item_total= item_total + v # or use item_total += v

    print("Total number of items: " + str(item_total))
#--------------------------------------------------------------
def addToInventory(inventory, addedItems):
    # your code goes here

    addedItemCount = {}                 #this turns the addedItems into a dictionary
    for item in addedItems:             #see pg 110 characterCount.py
        addedItemCount.setdefault(item, 0)
        addedItemCount[item] = addedItemCount[item] + 1

    #this merges inventory and addItemCount dictionaries into 3rd dict
    inventoryMerge = {**inventory, **addedItemCount}
    

    for item in inventory:  #add up the values of an item using get()
        for item in addedItemCount:
            inventoryMerge[item] = inventory.get(item, 0) + addedItemCount.get(item, 0)
    
    inventory = inventoryMerge  #rename the inventoryMerge dictionary
    
    return inventory

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

这就是我解决它的方法:

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

def displayInventory(inven):
    print('Inventory:')
    count=0
    for i,j in inven.items():
        print(str(j)+' '+i)
        count=count+j
    print('Total number of items: '+ str(count))

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

def addToInventory(inventory, addedItems):
    
    for i in inventory.copy():
        for j in addedItems:
            if i==j:
                inventory[i]+=1
            else:
                inventory.setdefault(j,1)
                
    return inventory

inv = addToInventory(inventoryD, dragonLoot)

displayInventory(inv)

¿ 如果您尝试添加已在库存中的物品怎么办?

inventory={'rope':1,'torch':2,'potion':99,'phoenix down':11}
dragonLoot={'rope':1,'dragon tail':1,'gold coin':'100','phoenix down':1}
def displayInventory(inventory):
    print("Inventory: ")
    totalnumber=0
    for k,v in inventory.items():
        totalnumber+=v
        print(k.title()+": "+str(v))
print("Total items:"+str(totalnumber))

def addToInventory(inventory,newstuff):
    for item in newstuff:
        if item in inventory.keys():
            print("Already in stock: "+item)
            inventory.update([item])
        else:    
            inventory.setdefault(str(item),1)
            inventory[item]+1

addToInventory(inventory,dragonLoot)
displayInventory(inventory)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM