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 85 tina 70 66 85 gana 70 60 81 jhon 59 90 60 排序后: jack 70 60 85 gana 70 60 81 tina 70 66 85 jhon 59 90 60
解釋:
studentList = sorted(studentList, key=lambda x:(-x.math, x.history, -x.chinese))
將studentList中的每個對象首先按math屬性由大到小排序,在math相等的情況下,按照history從小到大排序,在math和history均相等的情況下按chinese從大到小排序。