It came to my mind to write about this subject after a friend of mine have asked me how could he sort an object list, coincidently last week I have had a similar problem so I decided to write a blog post to help those who might be still looking for an answer. This is not about algorithms but about Python data model and how to use it for sorting.
Imagine that there is the following:
class Student(object): def __init__(self, name=None, mark=None): self.name = name self.mark = mark student_list = [ Student(name="Andre", mark=10), Student(name="da", mark=5), Student(name="Palma", mark=7), ]
and you are doing something like:
for x in xrange(0, len(student_list)): for i in xrange(x+1, len(student_list)): if student_list[i].mark > student_list[x].mark: student_list[i], student_list[x] = student_list[x], student_list[i]
that means you are doing it wrong as it is not pythonic and you are not making use of any of those cool features Python gives you.
Ideally you should use sorted python buildt-in function to do it. You can do it using one of the following methods.
1. Specifying a lambda.
student_list = sorted(student_list, key=lambda student: student.mark)
Also, as you may know lambda returns a callable object/function definition so you can do something like this:
def useattr(attr): def kicker(obj): return getattr(obj, attr) return kicker student_list = sorted(student_list, key=useattr('mark'))
In fact this is not that different of using attrgetter.
2. Specifying a compare method in the class. That would make the Student class to look something like:
class Student(object): def __cmp__(self, other): if self.mark > other.mark: return 1 elif self.mark < other.mark: return -1 else: return 0 def __init__(self, name=None, mark=None): self.name = name self.mark = mark student_list = [ Student(name="Andre", mark=10), Student(name="da", mark=5), Student(name="Palma", mark=7), ] student_list = sorted(student_list)
And that’s all. Have a look on this python doc page for more.