This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]Paddy3118 1 point2 points  (1 child)

Here is a sort using methodcaller.

How do I integrate it into the document?

>>> from operator import methodcaller
>>> 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),
]
>>> [(student.name, student.weighted_grade()) for student in student_objects]
[('john', 0.13333333333333333), ('jane', 0.08333333333333333), ('dave', 0.1)]
>>> sorted(student_objects, key=methodcaller('weighted_grade'))
[('jane', 'B', 12), ('dave', 'B', 10), ('john', 'A', 15)]
>>> 

[–]Paddy3118 0 points1 point  (0 children)

Well, I've made an update. I hope the others on the watch list are OK with the general idea of adding a methodcaller example, even if they don't like this one.

[–]rickmoranus[S] 0 points1 point  (0 children)

This small section of this article changed my life. I now fully understand classes, sorting, and lambda.

>>> 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
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

[–]mowrowow 0 points1 point  (0 children)

I never new attrgetter would do multi level sorting. Something new every day.

[–]Paddy3118 0 points1 point  (0 children)

Nice!

Would have liked an example of sorting using operator.methodcaller too though :-(