我想写一个名为addToInventory(inventory, addedItems)
的函数,其中
库存参数是代表玩家库存“物品”的字典,addedItems参数是类似dragonLoot的列表
该函数应将列表中的项目添加到玩家库存中
stuff = {'rope':1, 'torch':6, 'gold coins':42, 'dagger':1, 'arrow':12}
dragonLoot = ['gold coins', 'dagger', 'gold coins', 'gold coins', 'ruby']
def addToInventory(inventory, addedItems):
for n in range(0, len(addedItems)):
new_inv = inventory.copy()
for k, v in (new_inv.items()):
if k == addedItems[n]:
v += 1
else:
new_inv[str(addedItems[n])] = 1
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for key, value in inventory.items():
print(str(value) + ' ' + key)
item_total += v
print("Total number of itmes: " + str(item_total))
stuff = addToInventory(stuff, dragonLoot)
displayInventory(stuff)
但这个节目:
Traceback (most recent call last):
File "C:/Users/admin/AppData/Local/Programs/Python/Python38/Automate the boring stuff with python/testdict.py", line 21, in <module>
stuff = addToInventory(stuff, dragonLoot)
File "C:/Users/admin/AppData/Local/Programs/Python/Python38/Automate the boring stuff with python/testdict.py", line 8, in addToInventory
for k, v in (new_inv.items()):
RuntimeError: dictionary changed size during iteration
附言:我是编程新手,所以有人也可以详细解释我遗漏了什么或哪里错了。谢谢
不使用
collections
的替代解决方案:也许是最简单的解决方案,但它是有效的:
您可以使用
collections.Counter
来保持stuff
:输出:
如果不想使用
collections.Counter
模块,可以使用:输出:
相关问题 更多 >
编程相关推荐