Sort a list of Class Instances Python

PythonSorting

Python Problem Overview


I have a list of class instances -

x = [<iteminstance1>,...]

among other attributes the class has score attribute. How can I sort the items in ascending order based on this parameter?

EDIT: The list in python has something called sort. Could I use this here? How do I direct this function to use my score attribute?

Python Solutions


Solution 1 - Python

In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()

Solution 2 - Python

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

x.sort(key=operator.attrgetter('score'))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionInceptionView Question on Stackoverflow
Solution 1 - PythonkindallView Answer on Stackoverflow
Solution 2 - PythonNed BatchelderView Answer on Stackoverflow