方法一:
class Myobj:
def __init__(self,id,score):
self.id=id
self.score=score
if __name__ == '__main__':
array=[Myobj(1,5),Myobj(2,2),Myobj(3,0)]
array=sorted(array,key=lambda x:x.score)
for obj in array:
print(obj.id,obj.score)
方法二:
class Myobj:
def __init__(self,id,score):
self.id=id
self.score=score
def __lt__(self, other):
return self.score < other.score
if __name__ == '__main__':
array=[Myobj(1,5),Myobj(2,2),Myobj(3,0)]
array=sorted(array)
for obj in array:
print(obj.id,obj.score)
本文介绍了Python中对自定义对象进行排序的两种方法。方法一是使用`sorted`函数结合`key`参数指定排序依据;方法二是通过重写`__lt__`方法实现对象间的比较。这两种方法都可以按对象的`score`属性对Myobj类实例进行排序。
1448

被折叠的 条评论
为什么被折叠?



