我有一个名为Individual的类,该类具有变量self.fitness。我收集了这些个体实例,我想按它们的适合程度对其进行排序。如何在python中完成?
最佳答案
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]