Get a list of objects with the maximum attribute value in a list of objects

依然范特西╮ 提交于 2021-02-11 09:52:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!