1

Slightly different from previous questions. I have found here: front_Ar is a list of objects with a score attribute.

I am trying to get a list of all objects with the highest score. I have tried:

maxind = []
maxInd.append(max(front_Ar, key=attrgetter('score')))

which stored only one object (presumably the first one it found). Any idea how can this be done?

Community
  • 1
  • 1
Yair
  • 859
  • 2
  • 12
  • 27

2 Answers2

3

Find the max score first, then filter the list based on that score:

max_score = max(front_Ar, key=attrgetter('score')).score
max_ind = [obj for obj in front_Ar if obj.score == max_score]
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
0

The max() function can be used to find the value of the highest score.

To get the objects whose score matches that value, you could do a list comprehension like in @juanpa.arrivillaga's answer, or use something like filter() on the list to return only the items matching your criterion.

top_score = max(front_Ar, key=attrgetter('score')).score
max_ind = list(filter(lambda x: x.score == top_score, front_Ar))
CrannDarach
  • 81
  • 2
  • 3