我对编程仍然很陌生,在这里我遇到了一个问题,我似乎找不到一个好的答案。基本上,我做了一个小程序,可以让你添加和删除字典中的项目。这应该就像是一个来自RPG游戏的库存,您可以打开一个箱子,内容将被添加到库存中,当您使用物品时,它们将从库存中移除。我想设置它,如果清单中某个特定商品的数量为零或更少,那么该商品就会从字典中一起消失。这是我遇到麻烦的地方。这是我完成的程序如果值为零,则从库存(字典)中删除项目
inventory = {}
def add_to_inventory(item_tuple):
inventory[item_tuple[0]]=item_tuple[1]
def add_all_items(tuple_list):
for tup in tuple_list:
if tup[0] not in inventory:
add_to_inventory(tup)
else:
inventory[tup[0]]+=tup[1]
return inventory
def remove_items(item,quantity):
global inventory
updated_inventory={}
for key,value in inventory.items():
if key==item:
value-=quantity
inventory[key]=value
if inventory[key]<= 0:
inventory[key]=0
for key,value in inventory.items():
if value!=0:
updated_inventory[key]= value
inventory=updated_inventory
这里工作方案:
>>> chest=[("healing potion",3),("sword",1),("bread",5),("gold",50)]
>>> inventory
{}
>>> add_all_items(chest)
{'bread': 5, 'healing potion': 3, 'gold': 50, 'sword': 1}
>>> remove_items("bread",3)
>>> inventory
{'bread': 2, 'healing potion': 3, 'gold': 50, 'sword': 1}
>>> remove_items("bread",2)
>>> inventory
{'healing potion': 3, 'gold': 50, 'sword': 1}
>>>
我与前两个功能是如何看起来很高兴,但我remove_items功能看起来非常邋遢,我知道有即使它在技术上有效,也必须是更好的方式。我试着用“pop”和“del”,但是我会得到一个运行时错误,告诉我我的字典在迭代期间改变了大小。因此,现在我必须制作一个名为updated_inventory的全新库存,并且最终在迂回过程之后将其设置为等于“库存”时才是正确的。就像我刚才说的那样,我只有一个月的时间,所以我认为在这里我可以做得更好,但到目前为止,这是唯一有效的方法。从阅读中可以看出它看起来设计得很差。任何关于我能做得更好的建议?谢谢您的帮助。
我想跟踪清单中每个项目的数量。举例来说,如果我有四种药剂和两种药剂,我仍然希望库存证明我有一些剩余药物。我只想要将该项目从字典中删除,如果值<= 0。 –