Created
May 6, 2015 12:01
-
-
Save hanswillem/6d6fb4089b5008120d16 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #sort a list of object based on an attribute or a method of the object | |
| from operator import attrgetter, methodcaller | |
| class Person(object): | |
| def __init__(self, name, age): | |
| self.age = age | |
| self.name = name | |
| p1 = Person('Trijn', 101) | |
| p2 = Person('Jaap', 45) | |
| p3 = Person('Marie', 68) | |
| l = [p1, p2, p3] | |
| ls = sorted(l, key = attrgetter('age')) | |
| for i in ls: | |
| print i.name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment