如何获得列表中的第一个最大非重复元素?

时间:2020-06-05 07:20:42

标签: python

sentences = Iterator(...)

populations = [[0 1] [1 1] [0 1] [0 1]] score = [0, 6, 4, 4]

我想做的是首先获得best_score = max(score) chromosome_bestbest_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 = 6chromosome_bestscore之间的第一个匹配项

3 个答案:

答案 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给出了所有遇到的第一个最大值,因此我们得到了预期的结果。

此解决方案仅遍历列表一次。