为什么我的字典计数逻辑似乎忽略了额外的条目?

问题描述 投票:0回答:7

注意:这不是要求解决代码挑战的问题。这是一个询问特定调试问题的问题。除非您要解决问题,否则请勿发布答案。

我正在做一个 Python 编码挑战,我创建了一个项目清单。以下是我正在测试的代码:

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 的“金币”钥匙。这是为什么?

python dictionary
7个回答
6
投票

问题是你正在使用

set
:

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

输出:

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

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

解决方案:使用

list
代替:

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

输出:

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

0
投票

这就是我解决的方法:

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)

0
投票

我的版本将addedItems列表转换成字典。 它融合了两者 字典一起组成第三个字典。然后将两个字典的值相加,并将值存储到第三个字典中。
最后,它将第三个字典重命名为 inventory 并将其返回给 displayInventory 函数。 虽然不太优雅,但仍然是解决这个问题的另一种方法。

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)

-1
投票

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

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)

-1
投票
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)

-1
投票

这就是我解决的方法:

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)

-1
投票

这是我的解决方案,正在测试它,在里面添加更多项目只是为了看看它是否有效,看起来确实如此

stuff = {"rope": 1, "torch":6,"gold coin":42,"dagger":1, "arrow":12,"dragon":1 ,
         "legendary weapons": 3, "girls": 0,"wolf fangs": 33}

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

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

def addToInventory(inventory, addedItems):
    for item in addedItems:
        if item not in inventory.keys():
            inventory[item] = 1
        else:
            inventory[item]+=1

addToInventory(stuff,dragonLoot)
displayInventory(stuff)
© www.soinside.com 2019 - 2024. All rights reserved.