I have a class named Individual, which has a variable, self.fitness. I have a collection of these Individual instances and I'd like to sort them by their fitness. How is this done in python?
+5
A:
from operator import attrgetter
sorted(item_list, key=attrgetter('fitness'))
item_list can be any iterable. Here is an example
>>> class C(object):
... def __init__(self, fitness):
... self.fitness=fitness
... def __repr__(self):
... return "fitness: %s"%self.fitness
...
>>>
>>> from operator import attrgetter
>>> L=[C(10),C(4),C(1),C(99)]
>>> sorted(L, key=attrgetter('fitness'))
[fitness: 1, fitness: 4, fitness: 10, fitness: 99]
>>> S=set(L)
>>> sorted(S, key=attrgetter('fitness'))
[fitness: 1, fitness: 4, fitness: 10, fitness: 99]
gnibbler
2010-02-23 01:58:18
if it's self.fitness, would i use key=attrgetter('self.fitness')?
Chris
2010-02-23 02:05:28
No, attrgetter takes care of the dereferencing from self.BTW, `sorted(item_list)` returns a new list but leaves item_list unchanged. Instead, you can do `item_list.sort()` which will sort item_list in place, returning None.
Paul McGuire
2010-02-23 02:07:19
No, see the examples I added to my answer
gnibbler
2010-02-23 02:07:41