当我不知道某个元素是索引numb时,如何从列表中删除它

2024-06-16 11:47:01 发布

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

我正在做一个基于文本的冒险游戏,有点麻烦

我想删除一个项目从库存清单,但它的索引是未知的,因为用户可能会拿起其他项目之前,我试图删除一个

我该如何删除它

列表为:

inventory = ["sword", "healing potion"]

当你玩游戏的时候,你捡起物品,它就会被添加到这个列表中


Tags: 项目用户文本列表库存物品玩游戏inventory
2条回答

您可以简单地使用remove方法:

inventory.remove('sword')

以上答案是最好的。另一种方法是(也许这也有用):

index = inventory.index("sword") #in this way you get the index del(inventory[index]) #and now remove it

相关问题 更多 >