Python实现多属性排序
多属性排序:假如某对象有n个属性,那么先按某规则对属性a进行排序,在属性a相等的情况下再按某规则对属性b进行排序,以此类推。
现有对象Student:
class Student: def __init__(self, name, math, history, chinese): self.name = name self.math = math self.history = history self.chinese = chinese
多属性排序:
studentList = []studentList.append(Student('jack', 70, 60, 85))studentList.append(Student('tina', 70, 66, 85))studentList.append(Student('gana', 70, 60, 81))studentList.append(Student('jhon', 59, 90, 60))print("未排序:")for student in studentList: print(student.name,student.math,student.history,student.chinese)print("排序后:")# 排序,属性规则在sorted的key中指定studentList = sorted(studentList, key=lambda x:(-x.math, x.history, -x.chinese))for student in studentList: print(student.name,student.math,student.history,student.chinese)
运行结果:
未排序:jack 70 60 85tina 70 66 85gana 70 60 81jhon 59 90 60排序后:jack 70 60 85gana 70 60 81tina 70 66 85jhon 59 90 60
解释:
studentList = sorted(studentList, key=lambda x:(-x.math, x.history, -x.chinese))
将studentList中的每个对象首先按math属性由大到小排序,在math相等的情况下,按照history从小到大排序,在math和history均相等的情况下按chinese从大到小排序。