开发者

How to sort a collection of objects by an variable they all hold?

开发者 https://www.devze.com 2022-12-21 10:20 出处:网络
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开发者_运维知识

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号