Sort a list of Class Instances Python

python, sorting

Solution

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'))

Problem

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?

Original source

Related problems