gpt4 book ai didi

python - 如何从列表项更新字典?

转载 作者:行者123 更新时间:2023-11-28 20:36:18 25 4
gpt4 key购买 nike

我有以下问题:

假设我杀死了一条龙并且它掉落了战利品,我该如何根据战利品更新我的库存?我想出了如果元素栏中不存在战利品如何追加,但如果它们已经存在,我不确定如何更新它。

代码如下:

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)

最佳答案

你应该看看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)

关于python - 如何从列表项更新字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45387953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com