簡體   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