立即学习:https://edu.csdn.net/course/play/26755/340128?utm_source=blogtoedu
如果列表元素是对象,如何排序:
方法1:
class MyClass:
def __init__(self):
self.number = 0
def __lt__(self, other):
return self.number < other.number
class1 = MyClass()
class1.number = 20
class2 = MyClass()
class2.number = 10
class3 = MyClass()
class3.number = 30
a = [class1, class2, class3]
a.sort()
方法2:
class MyClass:
def __init__(self):
self.number = 0
def __gt__(self, other):
return slef.number > other.number
class1 = MyClass()
class1.number = 20
class2 = MyClass()
class2.number = 10
class3 = MyClass()
class3.number = 30
a = [class1, class2, class3]
a.sort()
方法3:
import operator
class MyClass:
def __init__(self):
self.number = 0
class1 = MyClass()
class1.number = 20
class2 = MyClass()
class2.number = 10
class3 = MyClass()
class3.number = 30
a = [class1, class2, class3]
a.sort(key = operator.attrgetter(‘number’))
如果列表元素是对象,如何倒序:
import operator
class MyClass:
def __init__(self):
self.number = 0
class1 = MyClass()
class1.number = 20
class2 = MyClass()
class2.number = 10
class3 = MyClass()
class3.number = 30
a = [class1, class2, class3]
a.sort(key = operator.attrgetter(‘number’), reverse = True)