向列表中的元素添加1并返回不同的lis

2024-05-08 01:26:18 发布

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

我编写了以下代码:

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,然后返回同一个列表,其中包含不同的值,但名称不同,因为以后我需要这两个值。我试着这样做,但它没有工作,我设法产生的价值,但我没有成功地把他们添加到正确的位置列表。有什么建议吗?你知道吗


Tags: 代码ingame元素列表forlendef
1条回答
网友
1楼 · 发布于 2024-05-08 01:26:18

这个答案假设您想向每个列表的第二项添加一个额外的元素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]]]

相关问题 更多 >