tags:

views:

48

answers:

1

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
if it's self.fitness, would i use key=attrgetter('self.fitness')?
Chris
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
No, see the examples I added to my answer
gnibbler