定义一个Student类,包含name和age。对于一个包含Student对象的列表,按 age 属性进行排序。
#python #class类 #对象属性 #排序
Python入门题045:根据对象属性进行排序
代码1:
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
li = [Student('小明', 11), Student('小红', 12),
Student('小青', 9)]
li.sort(key=lambda e: e.age)
print(li)
li = [Student('小明', 11), Student('小红', 12),
Student('小青', 9)]
li2 = sorted(li, key=lambda e: e.age)
print(li)
print(li2)
代码2:
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
def __lt__(self, other):
return self.age < other.age
li = [Student('小明', 11), Student('小红', 12),
Student('小青', 9)]
li.sort()
print(li)
页面更新:2024-03-06
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号