简体   繁体   English

我们如何根据 python 中的多个参数对对象列表进行排序

[英]How do we sort a list of objects based on multiple parameters in python

So my class is所以我的 class 是

class Student:
        
    raise_amt = 1.8
    no_of_students = 0
    def __init__(self, id, name, age, salary):
        self.id = id
        self.name = name
        self.age = age
        self.salary = salary
        
        
        Student.no_of_students+=1
        
    
    def __repr__(self):
        return "Student({}, {}, {}, {})".format(self.id, self.name, self.age, self.salary)
    
    
    def __str__(self):
        return "Student user: {}, name:{}, age:{}".format(self.id, self.name, self.age)   

And I have created an object with 3 objects我创建了一个带有 3 个对象的 object

s1 = Student(10, "Pranav", 21, 1200)
s2 = Student(20, "Pranav", 22, 1500)
s3 = Student(30, "tejas", 22, 5999)

students = []

students.append(s1)
students.append(s2)
students.append(s3)


The sort function given is给出的排序 function 是

students.sort(key = lambda x:x.name)

I WANT TO SORT THE LIST IN SUCH A WAY THAT IF NAMES ARE EQUAL, IT SHOULD THEN CHECK AGE AND IF THAT IS EQUAL ASWELL THEN SALARY我想以这样的方式对列表进行排序,如果名称相同,则应检查年龄,如果相同,则应检查薪水

Basically the equivalent of the comparator class in Java基本上相当于Java中的比较器class

To achieve what you want just return sorting key as a tuple of necessary fields:要实现您想要的,只需将排序键作为必要字段的元组返回:

students.sort(key = lambda x: (x.name, x.age, x.salary))

Try full working code here online . 在此处在线尝试完整的工作代码。

The best way is to implement magic methods like __gt__ ( https://docs.python.org/3/reference/datamodel.html#object.__gt__ ) in your class and let the standard operators do what they are supposed to do.最好的方法是在__gt__ The standard sort function will work like a charm letting the objects know how to compare themselves.标准sort function 将像一个魅力一样让对象知道如何比较自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM