Python Forum

Full Version: sorted object in list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
[python 3.7.2]

Hello so I already read how to do it and even try the exemple with student_objects.
So my problem is I want to sort a list by one of their attribut.
class Vents:
       def __init__(self, colonne,ligne): # Notre méthode constructeur
           self.col=colonne
           self.li=ligne
           self.direction =feuille1.cell_value(ligne,0)
           self.durée=feuille1.cell_value(self.li,self.col)
           self.nom=feuille1.cell_value(11,colonne)
I did a list of object Vents, 16 list for 16 differents directions.(each one of those contain 5 objects)
so I want to sort them by "durée" which is a int.
direction1=[5 object Vents] which their "durée" value is [5, 7, 0, 0, 0]
I type
sorted(direction1, key=lambda direction= direction.durée)
and when I print it it give me [5, 7, 0, 0, 0]

[the exemple]
class Student:
        def __init__(self, name, grade, age):
                self.name = name
                self.grade = grade
                self.age = age
        def __repr__(self):
                return repr((self.name, self.grade, self.age))
        def weighted_grade(self):
                return 'CBA'.index(self.grade) / float(self.age)

student_objects = [
        Student('john', 'A', 15),
        Student('jane', 'B', 12),
        Student('dave', 'B', 10),]

sorted(student_objects, key=lambda student: student.age)
gives me [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]
So it didn't work too.
Your student example works for me. It gave me [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]. Note that sorted creates a new list, it does not modify the original list. To sort the original list you would want the sort method of the list: student_objects.sort(key=lambda student: student.age).
thanks a lot that was only that. once again thank you. this topic is closed (I'm searching how to do that ahahh)