随机选择数组中的元素 - 满足条件

Choosing elements in an array randomly - satisfying conditions

我的项目需要帮助。以下是示例数据。

populations = [[1 1]
               [1 1]
               [1 0]
               [1 1]]

score = [0, 4, 0, 6]
avail_res = [4, 4]

代码如下所示:

chromosome = []
for num in score:
    if num <= avail_res[0] and num != 0:
        chromosome = populations[score.index(num)]
        print(chromosome)

        if len(chromosome) > 1:
           k = random.choice(chromosome)
           chromosome_best = [k[1]]
           print(chromosome_best)

        else:
           chromosome_best = [chromosome]
           print(chromosome_best)

objective就是在选中的chromosome/s中找出最好的染色体。对于上面的示例,由于只有 4(分数索引 1)满足代码中的条件,因此它应该从人口中给出 chromosome best = [1 1]。如果有多个分数满足条件,代码应随机选择 best_chromosome。例如,score = [4, 2, 2, 6]。我在分数中有三个元素满足条件 (4, 2, 2)。现在,在选择populations中的best_chromosome时,代码可以选择更高的一个,即4,并给出populations中对应的值。

问题是每当我尝试 运行 代码时,对于所选的 chromosome_best = [1 0](只是一个例子),我得到的长度是 2,对应于1 和 0。但我的目的只是得到 length = 1 for [1 0]3 如果染色体是 [1 0] [1 1] [1 0]。这样,我就可以使用上面的代码随机选择了。

任何 help/suggestion 将不胜感激!谢谢!

我建议制作 chromosome 列表列表 -- 并可能将其重命名为 chromosomes 以使其清楚。

而不是 chromosome = populations[score.index(num)],使用 chromosomes.append(populations[score.index(num)])

完整的代码片段如下:

chromosomes = []
for num in score:
    if num <= avail_res[0] and num != 0:
        chromosomes.append(populations[score.index(num)])
        print(chromosomes)

        if len(chromosomes) > 1:
           k = random.choice(chromosomes)
           chromosome_best = k[1]
           print(chromosome_best)

        else:
           chromosome_best = chromosomes
           print(chromosome_best)