如何通过它们都拥有的变量对对象集合进行排序?

时间:2010-02-23 01:57:40

标签: python sorting

我有一个名为Individual的类,它有一个变量self.fitness。我收集了这些个人实例,我想根据他们的健康状况对它们进行排序。这是如何在python中完成的?

1 个答案:

答案 0 :(得分:6)

from operator import attrgetter
sorted(item_list, key=attrgetter('fitness'))

item_list可以是任何可迭代的。这是一个例子

>>> 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]