How to sort a collection of objects by an variable they all hold?
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 pyth开发者_运维知识库on?
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]
精彩评论