python - 如何按属性对列表进行排序
问题描述
是的,我看过其他帖子,但我仍然有点困惑,有些人使用 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
解决方案
使用 Sorted() 函数调用 sorted(iterable, key: NoneType=None) ,将对象列表作为可迭代对象
推荐阅读
- javascript - QWebEngine - 如何从 C++ 捕获任何 javascripts 的执行?
- node.js - 发生未处理的异常:无法从“/ang-frontend”找到模块“@angular-devkit/build-angular”。使用 docker 和 docker-compose
- python - 复制到 lambda 中的新变量
- javascript - 如何使用 ramda 的 sortBy 函数按降序排序?
- android - 创建通知消息
- javascript - Javascript或JQuery中div的抛物线动画
- javascript - 在电子的主要过程之外创建菜单栏
- django - Django DRF 使用 JWT 获取缺少的 Auth 标头,但在 ReadOnly 视图上具有权限和身份验证
- python - 'str' 对象不能解释为整数:Python 错误
- php - 在 WP 插件中返回而不是回显