我在python中编写文本冒险。我有一个警长NPC会计算item
中的所有player.inventory
个对象,如果item.name == "dead goblin"
,那么该项目会从列表中删除,goblins_taken += 1
:
if "sheriff" in player.action and "talk" in player.action and player.location == sheriff:
goblins_taken = 0
for item in player.inventory:
if item.name == "dead goblin":
goblins_taken += 1
player.inventory.remove(item)
write("The sheriff says, 'Good job. You have killed " + str(goblins_taken) + " goblins!")
这段代码的问题在于,如果玩家杀死了2个妖精,警长会说玩家杀了1个妖精,而不是2个。
我试图简化IDLE中的问题,并意识到这是一个索引问题:
>>> foo = ['a', 'b', 'c', 'd', 'e']
>>> foo[2]
'c' # With b
>>> foo.remove('b')
>>> foo[2]
'd' # Without b, index is shifted down
是否有更好的方法可以从列表中删除list.remove()
项?或者有什么方法可以解决这个问题吗?
答案 0 :(得分:2)
你永远不应该修改你正在迭代的列表! 您可以通过创建第二个列表来解决它:
temp_inventory = list(player.inventory)
for item in player.inventory:
if item.name == "dead goblin":
goblins_taken += 1
temp_inventory.remove(item)
player.inventory = temp_inventory
我已经尝试过并且工作:
a = [1,2,3,2,1]
b = list(a)
elems_removed = 0
for elem in a:
if elem == 2:
elems_removed += 1
b.remove(elem)
print(a)
print(b)
a=b
print(a)
print(elems_removed)