首页 > 解决方案 > 我需要帮助从类函数的列表中删除条目

问题描述

在我正在编写的一个程序中,每当玩家攻击敌人时,都会运行一个 if 语句来检查目标的健康状况:

    def attack(self, target):
        target.stats.health = target.stats.health - self.stats.damage
        if target.stats.health <= 0:
            if isinstance(target, Enemy) == True:
                print(target.name, "has died")
                del #Something here to delete the target from the list of enemies
                #For example, in myPlayer.attack(enemies[0])
                #The target is enemies[0]
            else:
                pass
        else:
            print(target.name, "has", target.stats.health, "health left")

在我的代码中,创建了 Enemy 类的实例来创建敌人,这些实例都被放入一个列表中。如果目标的健康状况低于,我想要做的是删除列表条目。我知道目标本身是对我的敌人实例的引用,所以使用del target只会删除该引用。有没有一种方法可以让我实际调用参数条目或其他东西并将其删除?因此,如果我输入myPlayer.attack(enemies[x]),该del函数将作为del enemies[x].

标签: pythonlistclass

解决方案


推荐阅读