Skip to content

如果列表元素是对象如何排序 #41

@Sogrey

Description

@Sogrey
class MyClass:
    def __init__(self):
        self.value = 0

    def __gt__(self, other):
        return self.value > other.value

    '''
    def __lt__(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)  
# [<__main__.MyClass object at 0x0000026B3FD5DA90>, <__main__.MyClass object at 0x0000026B3FD5DB00>, <__main__.MyClass object at 0x0000026B3FD5DB70>]

import operator


#a.sort()  # 
a.sort(key = operator.attrgetter('value'))  # 根据对象的 value 排序
b = sorted(a,key = operator.attrgetter('value'))



降序排序
#a.sort(key = operator.attrgetter('value'),reverse=True)  # 根据对象的 value 排序  reverse=True 降序
a.sort()
print(a[0].value)
print(a[1].value)
print(a[2].value)

为类添加__gt__和__lt__方法,可以让该类的实例支持sort方法和sorted函数

通过改变__gt__和__lt__方法的返回值,或者设置sort方法和sorted函数的reverse参数,可以让列表倒序排列。

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions