Reputation: 73
populations = [[0 1]
[1 1]
[0 1]
[0 1]]
score = [0, 6, 4, 4]
best_score = max(score)
What I want to do is to get chromosome_best
by first, matching
best_score
with score
and get the index that match in score
, then using this index, get its corresponding value in populations
My code so far looks like this:
chromosome_best = numpy.array([d for a, d in zip(score, populations) if a == best_score])
But how could I change it such that when score has non-unique values, example:
score = [6, 6, 0, 4]
best_score = 6
The chromosome_best
that would be read is the first match between score
and best_score?
Upvotes: 2
Views: 78
Reputation: 18306
You can use max
with a key function:
chromosome_best, best_score = max(zip(populations, score), key=lambda tup: tup[1])
So we zip them together and max
determines the maximum of tuples zip
gives by looking at their element at 1
st index i.e. the score. We unpack the result to get best chromosome (and also best score). max
gives the first maximum value encountered among all, so we get the desired result.
This solution traverses the lists only once.
Upvotes: 0
Reputation: 190
The following code snippets should give the first match.
next(d for a, d in zip(score, populations) if a == best_score)
Upvotes: 0
Reputation: 2720
Something like populations[score.index(best_score)]
should do the trick. list.index
returns the first index where the list matches the element you provide, therefore it will always match with the first occurrence, no matter how many there are
Upvotes: 2