类中按成员属性排序

2024-05-16 22:23:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我在研究一个遗传算法问题。假设我有一个Population()类,它有一个Individual()列表。每个人都有一个与之相关的分数。根据这些人在人群中的得分对他们进行排序的好方法是什么?例如:

class Individual(object):
    rr = 100
    def __init__(self):
        self.score = random.randrange(self.rr)

class Population(object):
    def __init__(self, size):
        self.size = size
        self.population = [Individual() for _ in xrange(self.size)]

pop = Population(5)
for i in xrange(pop.size):
    print pop.population[i].score

有没有一个Pythonic的方法来根据他们的分数来分类这些人?谢谢!你知道吗


Tags: 方法selfforsizeobjectinitdefrr
3条回答

不导入任何库:

pop.population.sort(key=lambda x: x.score)

当然,请将key参数用于.sort()方法:

from operator import attrgetter
pop.population.sort(key=attrgetter('score'))

使用^{}使这变得更容易,但不是必需的。你知道吗

请参阅pythonwiki上的Sorting Howto,以获取更多提示和技巧。你知道吗

sorted_pop = sorted(pop.population, lambda x, y: cmp(x.score, y.score))

相关问题 更多 >