2024-简单点-如何给类对象排序

  1. 使用lambda匿名函数
>>> class Student:
	 def __init__(self, name, grade, age):
		 self.name = name
		 self.grade = grade
		 self.age = age
	 def __repr__(self):
 		return repr((self.name, self.grade, self.age))
 >>> student_objects = [ Student('john', 'A', 15),Student('jane', 'B', 12),Student('dave', 'B', 10),]
 >>> sorted(student_objects, key=lambda student: student.age) # sort by age
 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
  1. 使用operator库中的attrgetter
 >>> sorted(student_objects, key=attrgetter('grade', 'age'))
 [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
 
 >>> sorted(student_objects, key=attrgetter('age'))
 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

 sorted(student_objects, key=attrgetter('age'), reverse=True)
 [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
  1. functools中的total_ordering自定义排序顺序
 >>> Student.__lt__ = lambda self, other: self.age < other.age
 >>> sorted(student_objects)
 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

不过,请注意<在__lt__()未被实现时可以回退为使用__gt__()(请参阅object.lt()
了解相关机制的细节)。为避免意外,PEP8建议实现所有的六个比较方法。total_ordering()
装饰器被提供用来令此任务更为容易。

from functools import total_ordering

@total_ordering
class MyComparableClass:
    def __init__(self, value):
        self.value = value
    
    def __eq__(self, other):
        if isinstance(other, MyComparableClass):
            return self.value == other.value
        return NotImplemented
    
    def __lt__(self, other):
        if isinstance(other, MyComparableClass):
            return self.value < other.value
        return NotImplemented

# 现在 MyComparableClass 实例可以使用所有比较运算符
a = MyComparableClass(5)
b = MyComparableClass(10)
c = MyComparableClass(5)

print(a < b)  # 输出: True
print(a == b) # 输出: False
print(a > c)  # 输出: False
print(a <= c) # 输出: True
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

万物琴弦光锥之外

给个0.1,恭喜老板发财

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值