如何在列表中获取max对象并替换它?

时间:2017-03-04 15:53:55

标签: python python-2.7 python-3.x

我正在研究遗传算法,定义了一个类:

class Solution:
    def __init__(self, N=1, K=1):
        self.wi = {}
        self.loss = 0
        id = random.sample([i for i in range(N)], K)
        wi = [random.random() for _ in range(K)]
        for i in range(K):
            self.wi[id[i]] = wi[i]

生成obj

列表
population = [Solution(N, K) for _ in range(100)]

在我的算法中,将从C列表中创建一个新的obj population,并将population中的obj替换为最大的loss

我试过

largest = max(population, key = attrgetter('loss'))
largest = C

但是列表中的obj不会随largest而改变,我该怎么做才能实现这一目标?

2 个答案:

答案 0 :(得分:2)

您可以计算最大索引,然后设置该索引的填充,而不是计算最大对象:

largest_i = max(range(len(population)),key=lambda i:population[i].loss)

然后设置:

population[largest_i] = C

这只会扫描一次列表。

答案 1 :(得分:0)

替换

from operator import attrgetter

largest = max(population, key = attrgetter('loss'))
largest = C

largest = max(population, key = attrgetter('loss'))
population[population.index(largest)] = C