Custom Search

Wednesday, February 27, 2013

How To Python Sorting Objects with attributes

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))



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

sorted(student_objects, key=lambda student: student.age) ###sort by age
* "key" parameter to specify a function to be called on each list element prior to making comparisons.

sorted(student_objects, key=lambda student: student.age, reverse=True)

import operator
sorted(student_objects, key=operator.attrgetter('age'))

No comments:

Post a Comment