如何从列表项更新词典?

2024-10-02 12:31:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下问题:

想象我杀死了一条龙,它掉落了战利品,我如何从战利品中更新我的库存?我想如何追加如果战利品不存在的库存,但如果他们已经在那里,我不知道如何更新它。你知道吗

代码如下:

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

def showstuff(storeno):
items_total = 0
for k, v in storeno.items():
    print('Item :' + k + '---' + str(v))
    items_total = items_total + v
print('Total Items:' + str(items_total))

'''def addstuff(inventory, additem):
    I'm not sure what to do here

dragonloot = ['gold coin', 'gold coin', 'rope']
addstuff(UserInventory, dragonloot)'''
showstuff(UserInventory)

Tags: def库存itemstotalcoinprintropestr
2条回答

你应该看看Counters

from collections import Counter

inventory = {'rope': 1, 'torch':6, 'gold coin':42, 'dagger': 1, 'arrow': 12}
inventory_ctr = Counter(inventory)

update = ['rope', 'torch']
update_ctr = Counter(update)

new_inventory_ctr = inventory_ctr + update_ctr

print(new_inventory_ctr)

您可以使用以下示例代码。。。你知道吗

def addstuff(inventory, additem):
    for newitem in additem:
        if newitem in inventory:
            inventory[newitem] += 1
        else:
            inventory[newitem] = 1

相关问题 更多 >

    热门问题