0

I have a list of class objects:

list = [x, y, z]

But I want to sort them like integers (they have an integer variable defined in them that I want to sort by (I access it by doing list[x].score)), but I don't know how to.

How can I sort this? (the list has a variable length)

Ideally, something like this:

list = [x, y, z]  # x.score = 2, y.score = 3, z.score = 1
list.sort()  # Or something
# list = [z, x, y]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
someone
  • 19
  • 3
  • It is very important to understand, "class objects" means the classes themselves. You mean *instances of a class*, although note, `int` objects are instances of a class, the class `int`... *Everything in Python is an instance of a class (even classes themselves)* – juanpa.arrivillaga Apr 30 '23 at 19:18

2 Answers2

2

sorted_list = sorted(objslist, key=lambda obj:obj.score)

Anr
  • 332
  • 3
  • 6
1

You can use the key= keyword argument of the .sort() method. All you do is pass it a function or lambda that returns what you really want to sort the objects by:

lst = [x, y, z]
lst.sort(key=lambda x: x.score)

Or, here's a fuller example:

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

    def __repr__(self):
        return str(self.score)


lst = [ScoreHolder(2), ScoreHolder(3), ScoreHolder(1)]
print(lst)

lst.sort(key=lambda x: x.score)
print(lst)
Michael M.
  • 10,486
  • 9
  • 18
  • 34