我正在研究遗传算法,定义了一个类:
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
而改变,我该怎么做才能实现这一目标?
答案 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