Skip to content

Instantly share code, notes, and snippets.

@hanswillem
Created May 6, 2015 12:01
Show Gist options
  • Save hanswillem/6d6fb4089b5008120d16 to your computer and use it in GitHub Desktop.
Save hanswillem/6d6fb4089b5008120d16 to your computer and use it in GitHub Desktop.
#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