首页 > 解决方案 > 如何按属性对列表进行排序

问题描述

是的,我看过其他帖子,但我仍然有点困惑,有些人使用 lambda 或制作多种方法,我很困惑。我有这个类,我想创建多个实例(团队成员),在我调用我的函数开始战斗之前,我想安排一个列表,以便 self.full_speed 最高的人先走,等等。 (我有一个用于 debuffs/buffs 的 full_speed 和 speed 属性)


class Player:
    """Describes the main player."""
    def __init__(self, level, health, will, speed):
        """Initializes stats"""
        self.level = level
        self.health = health
        self.full_health = health
        self.will = will
        self.full_will = will
        self._cheat = "cheat" # Protected instance attribute has a leading underscore
        # Private starts with two leading underscores
        self.speed = speed
        self.full_speed = speed

    def level_up(self, skill):
        """Choose where to distribute skill points."""
        pass

    def default_attack(self, enemy):
        """Normal attack that damages enemy target."""
        damage = 0
        if random.randint(1,100) <= 95:
            damage = (self.level * 2)
            critical_hit = random.randint(1,10)
            if critical_hit == 1:
                damage += int(self.level * 0.5)
                print("Critical hit!")
        enemy.health -= damage
        print("The enemy took " + str(damage) + " damage.")

    def special_attack(self, enemy):
        """Deals more damage but uses will, more likely to miss."""
        damage = 0
        if random.randint(1,100) <= 90:
            damage = (self.level * 3)
            critical_hit = random.randint(1, 10)
            if critical_hit == 1:
                damage += self.level
                print("Critical hit!")
        enemy.health -= damage
        self.will -= 2
        print("The enemy took " + str(damage) + " damage.")

    def heal(self):
        """Heals self by 10%."""
        self.will -= 2
        recovered = int(self.full_health * 0.10)
        self.health += recovered
        if self.health > self.full_health:
            self.health = self.full_health
        print("Recovered " + str(recovered) + " HP.")

我已经从这里开始了,但我不确定现在该去哪里..

def team_by_speed(team):
    new_team = []
    for member in team:
        # member.full_speed
    return new_team

标签: python

解决方案


使用 Sorted() 函数调用 sorted(iterable, key: NoneType=None) ,将对象列表作为可迭代对象


推荐阅读