zoukankan      html  css  js  c++  java
  • Python实现多属性排序

    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从大到小排序。

     

     

  • 相关阅读:
    1451. Rearrange Words in a Sentence
    1450. Number of Students Doing Homework at a Given Time
    1452. People Whose List of Favorite Companies Is Not a Subset of Another List
    1447. Simplified Fractions
    1446. Consecutive Characters
    1448. Count Good Nodes in Binary Tree
    709. To Lower Case
    211. Add and Search Word
    918. Maximum Sum Circular Subarray
    lua 时间戳和时间互转
  • 原文地址:https://www.cnblogs.com/thisyan/p/9867372.html
Copyright © 2011-2022 走看看