程序员Python

Python基数(12) - 如何对列表元素是对象的排序

2020-02-25  本文已影响0人  xianling_he

列表元素是对象,对这样的列表排序方法

class MyClass:
    def __index__(self):
        self.value = 0

    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]


a.sort()
print(a[0].value)
print(a[1].value)
print(a[2].value)
image.png
class MyClass:
    def __index__(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]


a.sort()
print(a[0].value)
print(a[1].value)
print(a[2].value)
image.png
class MyClass:
    def __index__(self):
        self.value = 0

my1 = MyClass()
my1.value = 20

my2 = MyClass()
my2.value = 10

my3 = MyClass()
my3.value = 30

import operator   #导入operator

a = [my1,my2,my3]

a.sort(key=operator.attrgetter('value'))
b = sorted(a,key=operator.attrgetter('value'))


print(a[0].value)
print(a[1].value)
print(a[2].value)

print('b:',b[0].value)
image.png

列表元素是对象,对这样的列表如何进行倒序排列

class MyClass:
    def __index__(self):
        self.value = 0

my1 = MyClass()
my1.value = 20

my2 = MyClass()
my2.value = 10

my3 = MyClass()
my3.value = 30

import operator

a = [my1,my2,my3]

a.sort(key=operator.attrgetter('value'),reverse=True)
b = sorted(a,key=operator.attrgetter('value'))


print(a[0].value)
print(a[1].value)
print(a[2].value)
image.png
    def __lt__(self, other):
        return self.value > other.value

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

总结

1.为类添加gt & lt 的方法,可以让类的实例支持sort,sorted函数
2.通过改变gt & lt方法的返回值,或者设置一下sort,sorted函数的reverse参数,就可以让列表倒序排列

上一篇下一篇

猜你喜欢

热点阅读