【问题标题】:Choosing elements in an array randomly - satisfying conditions随机选择数组中的元素 - 满足条件
【发布时间】:2020-06-09 11:18:34
【问题描述】:

我的项目需要帮助。以下是样本数据。

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)

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

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

任何帮助/建议将不胜感激!谢谢!

【问题讨论】:

    标签: python python-3.x random selection


    【解决方案1】:

    我建议将chromosome 设为列表列表——也许将其重命名为chromosomes 以明确这一点。

    使用chromosomes.append(populations[score.index(num)]),而不是chromosome = 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)
    

    【讨论】:

    • 非常感谢!除了您的评论之外,我所做的就是使染色体最好成为一个 numpy 数组,因为每当我尝试运行代码时,我都会得到一个输出 = [array([1, 0])]。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多