You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python中PriorityPerson类的__lt__魔法方法以实现正确排序?

Fixing the PriorityPerson lt Method for Correct Sorting

Let's break down what's wrong with your current __lt__ implementation and fix it to match your sorting rules:

What's Wrong with the Original Code

Your __lt__ method is overly verbose and contains logical errors:

  • When comparing objects with different deficiente states, you incorrectly still check the name—all deficiente=True objects should come before deficiente=False ones, regardless of their names.
  • The same-state branches are redundant and in some cases, the return logic is needlessly convoluted (though it might accidentally work, it's hard to maintain).

Correct Implementation

We can simplify the __lt__ logic to directly match your requirements:

  1. First compare the deficiente status: deficiente=True objects are "smaller" (should sort first) than deficiente=False ones.
  2. If statuses are identical, fall back to lexicographical sorting by name (just like the base Person class).

Here's the revised PriorityPerson class:

class PriorityPerson(Person):
    def __init__(self, name, deficiencia):
        super().__init__(name)
        self.deficiente = deficiencia
    
    def __lt__(self, other):
        # Handle differing deficiente states first
        if self.deficiente != other.deficiente:
            # True is considered "less than" False
            return self.deficiente
        # Same state: sort by name lex order
        return self.name < other.name

How This Works

  • When self.deficiente and other.deficiente differ: return self.deficiente does exactly what we need. If self is deficiente=True and other is False, it returns True (so self comes first). If self is False and other is True, it returns False (so other comes first).
  • When states are the same, we just compare names lexicographically, which aligns with your requirement.

Test the Fixed Code

Using your sample input:

p1 = PriorityPerson("John Smith", False)
p2 = PriorityPerson("Sam Mendes", False)
p3 = PriorityPerson("Grandmother Anne", True)
p4 = PriorityPerson("Stephen Hawking", True)
p5 = PriorityPerson("Betty Large", True)
listaPessoas = [p1,p2,p3,p4, p5]
listaPessoas.sort()
for p in listaPessoas:
    print(p)

You'll get the expected output:

Betty Large
Grandmother Anne
Stephen Hawking
John Smith
Sam Mendes

内容的提问来源于stack exchange,提问作者Tiago Verissimo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:13:12