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
方法二:
2. 如果列表元素是对象,进行倒序排列的方法有哪些?
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/245465.html