我写了以下代码:
population = [[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [1], [0]],
[[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]],
[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]],
[[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [3], [3]]]
def ManipulateFitness(population):
mf=[]
populaion_m = population
for game in range (0, len(population)):
m = [f+1 for f in population[game][1]]
mf.append(m)
manipulted = [m for f in population[game][1] for m in mf
population_m.append(manipulated)
return (population_m)
我想要做的只是为每个染色体添加1到列表中的第二个元素(第三个只是一个计数器),并返回相同的列表,只有这个不同的值,但具有不同的名称,因为生病需要以后。我是这样尝试但它没有用,我设法生成值但我没有成功将它们添加到正确位置的列表中。有什么建议吗?
答案 0 :(得分:1)
此答案假设您要在每个列表的第二项中添加其他元素1
:
population = [[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [1], [0]], [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]], [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]], [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [3], [3]]]
new_population = [[b+[1] if i == 1 else b for i, b in enumerate(a)] for a in population]
输出:
[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [1, 1], [0]], [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3, 1], [1]], [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4, 1], [2]], [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [3, 1], [3]]]
但是,如果您只想增加第二个列表中的元素,可以尝试:
new_population = [[[b[0]+1] if i == 1 else b for i, b in enumerate(a)] for a in population]
输出:
[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [2], [0]], [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [4], [1]], [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]], [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [4], [3]]]