前言:
在Python中经常会自定义数据类型,有时需要将自定义的数据类型排序,这时传统的方式就失效了。本文将解决这个问题。
一、创建一个自定义数据类型
from dataclasses import dataclass
@dataclass
class Student():
name:str
score:int
二、创建一个自定义数据类型的list
exam_scores = []
exam_scores.append(Student('Tom',50))
exam_scores.append(Student('Lily',80))
exam_scores.append(Student('Json',70))
exam_scores.append(Student('Jerry',60))
三、正常输出时
Student(name='Tom', score=50)
Student(name='Lily', score=80)
Student(name='Json', score=70)
Student(name='Jerry', score=60)
四、对List按照score排序
sorted_list = sorted(exam_scores,key=lambda x:x.score)
五、排序后的输出结果
Student(name='Tom', score=50)
Student(name='Jerry', score=60)
Student(name='Json', score=70)
Student(name='Lily', score=80)
总结:
可以看到List中的自定义数据类型按照Score进行了递增排序。