其他分享
首页 > 其他分享> > 020 列表元素是对象,如何排序

020 列表元素是对象,如何排序

作者:互联网

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. 如果列表元素是对象,进行倒序排列的方法有哪些?

标签:__,my1,self,value,列表,020,MyClass,排序,my3
来源: https://www.cnblogs.com/yuminhu/p/16058240.html