tags:

views:

52

answers:

2

I have a list of class instances -

x = [<iteminstance1>,...]

among other attributes the class has score attribute. How can I sort the items in ascending order based on this parameter?

EDIT: The list in python has something called sort. Could I use this here? How do I direct this function to use my score attribute?

+8  A: 
import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

x.sort(key=operator.attrgetter('score'))
Ned Batchelder
wow! is it that simple!! Just checked. It is :)
Inception
Welcome to Python! For sake of completness: the "key" parameter to srot functions/methods accepts a function as its parameter. The operator module provides usefull functions to tasks that are ordinarily done by the language Syntax itself - like an "add" function to do the same the " + " token does in the language, and in this case the attrgetter to do the same the " . " connector does in the syntax. Other parameters to "key" can be inplace functions defined with "lambda". In this case, sorted_x = sorted(x, lambda x: x.score)) - would have worked as well. The given example is better, though.
jsbueno
I'm not sure using `attrgetter` is better. Lambdas seems to be just as fast, and look cleaner IMO.
adw
+3  A: 

In addition to the solution you accepted, you could also implement the special __lt()__ ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()
kindall
@kindall. thanks!
Inception