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

     

     

  • 相关阅读:
    Angular中文api
    Angular各版本和组件下载
    判断一个浏览器是否支持opacity
    查找函数参数名称
    运行时代码求值
    简单的动画引擎
    利用闭包特性改写addEventListener的回调函数
    springboot指定redis库编号配置实现
    springboot获取IOC(ApplicationContext)实例
    ajax-springMVC提交表单的方式
  • 原文地址:https://www.cnblogs.com/thisyan/p/9867372.html
Copyright © 2011-2022 走看看