sentences = Iterator(...)
populations = [[0 1]
[1 1]
[0 1]
[0 1]]
score = [0, 6, 4, 4]
我想做的是首先获得best_score = max(score)
chromosome_best
与best_score
并在score
中获得匹配的索引,然后使用该索引在score
中获得其对应的值
到目前为止,我的代码如下:
populations
但是,当分数具有非唯一值时,如何更改它,例如:
chromosome_best = numpy.array([d for a, d in zip(score, populations) if a == best_score])
score = [6, 6, 0, 4]
将要读取的best_score = 6
是chromosome_best
和score
之间的第一个匹配项
答案 0 :(得分:2)
应该使用populations[score.index(best_score)]
之类的方法。 list.index
返回列表与您提供的元素匹配的第一个索引,因此,无论有多少个元素,它始终与第一个匹配。
答案 1 :(得分:0)
以下代码段应给出第一个匹配项。
next(d for a, d in zip(score, populations) if a == best_score)
答案 2 :(得分:0)
您可以将max
与按键功能一起使用:
chromosome_best, best_score = max(zip(populations, score), key=lambda tup: tup[1])
因此,我们将它们压缩在一起,max
通过查看位于zip
第一个索引(即分数)的元素来确定1
给出的元组的最大值。我们解压缩结果以获得最佳染色体(以及最佳分数)。 max
给出了所有遇到的第一个最大值,因此我们得到了预期的结果。
此解决方案仅遍历列表一次。