1.如果列表元素是对象,对这样的列表排序有哪些方法?
class MyClass: def __init__(self): self.value = 0 my1 = MyClass() my1.value = 20 my2 = MyClass() my2.value = 10 my3 = MyClass() my3.value = 30 a = [my1, my2, my3] print(a) a.sort()
TypeError: '<' not supported between instances of 'MyClass' and 'MyClass'
[<__main__.MyClass object at 0x0000020B8C4F9CC8>, <__main__.MyClass object at 0x0000020B8C4FC248>, <__main__.MyClass object at 0x0000020B8C4FD748>]
方法一:利用magic函数:__lt__ 或 __gt__
class MyClass: def __init__(self): self.value = 0 def __lt__(self, other): return self.value < other.value def __gt__(self, other): return self.value > other.value my1 = MyClass() my1.value = 20 my2 = MyClass() my2.value = 10 my3 = MyClass() my3.value = 30 a = [my1, my2, my3] print(a) a.sort() print(a[0].value) print(a[1].value) print(a[2].value)
[<__main__.MyClass object at 0x0000016E82E16808>, <__main__.MyClass object at 0x0000016E82E16BC8>, <__main__.MyClass object at 0x0000016E82E16B08>]
10
20
30
方法二:利用operator sort的key
class MyClass: def __init__(self): self.value = 0 my1 = MyClass() my1.value = 20 my2 = MyClass() my2.value = 10 my3 = MyClass() my3.value = 30 a = [my1, my2, my3] print(a) import operator a.sort(key = operator.attrgetter('value')) print(a[0].value) print(a[1].value) print(a[2].value)
方法三:利用operator sorted 的key
class MyClass: def __init__(self): self.value = 0 my1 = MyClass() my1.value = 20 my2 = MyClass() my2.value = 10 my3 = MyClass() my3.value = 30 a = [my1, my2, my3] print(a) import operator b = sorted(a, key=operator.attrgetter('value')) print(b) print(b[0].value) print(b[1].value) print(b[2].value)
2. 如果列表元素是对象,进行倒序排列的方法有哪些?
最简单方法
import operator a.sort(key = operator.attrgetter('value'), reverse=True)
或者更改__lt__或__gt__
def __lt__(self, other): return self.value > other.value
a.sort()
3. 总结
为类添加__lt__或__gt__方法,可以让该类的实例支持sort方法和sorted函数
通过改变__lt__或__gt__方法的返回值,或者设置sort方法和sorted函数的reverse参数,可以让列表倒序排列