- 使用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)]
- 使用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)]
- 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