列表元素是对象,对这样的列表排序方法
- 添加类方法使用lt
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
- 添加类方法使用gt
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
- 使用operator类
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
列表元素是对象,对这样的列表如何进行倒序排列
- 添加参数reverse = True
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
- 将lt,gt的符号改成相反的即可
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参数,就可以让列表倒序排列
网友评论