0

I'm trying to return an individual from the list that has fitness greater than or equal to 90. To do so I have to sort the list, but I think there is a better way.. how can I do this withought sorting. Like at the instant when the if condition becomes true print that perticular individual from the list.

    if any(individual.fitness >= 90 for individual in individuals):
        print('Threshold met!')
        individuals = sorted(
            individuals, key=lambda individual: individual.fitness, reverse=True)
        return individuals[0]

2 Answers2

0

Here you are :) :

for individual in individuals:
    if individual.fitness >= 90:
        print('Threshold met!')
        return individual
return None
Claudio
  • 7,474
  • 3
  • 18
  • 48
-1
list = [11, 35, 90, 95, 98, 89, 85]
list2 = [i for i in list if i>= 90]
print(list2)

Output of the above code is: [90, 95, 98]

It will return the list of values of your criteria. If you want to get every element individually, add these kines:

for individual in list2:
    print (individual) 

These lines will give this output:

90 95 98

Shivam Pandya
  • 251
  • 3
  • 10