问题
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?
回答1:
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]
回答2:
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))
来源:https://stackoverflow.com/questions/42169655/get-a-list-of-objects-with-the-maximum-attribute-value-in-a-list-of-objects