[Python] How to sort instances by instance variables

Not limited to Python, when writing a program, there are many opportunities to sort lists (arrays) and dictionaries. And many of those methods are introduced in blog articles and so on.

However, less often than lists and dictionaries, there are times when you want to sort a list of instances by instance variables. For example, if you have the following class called Student, you might sort the list of instances named students by score.

class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

a = Student('Taro', 70)
b = Student('Hanako', 90)
c = Student('Jiro', 80)
students = [a, b, c]

In such a case, if you use the operator.attrgetter function, it will take a few lines (almost one line) as follows. Can write.

from operator import attrgetter
students.sort(key=attrgetter('score'))
for s in students:
    print(s.name, s.score)
Taro 70
Jiro 80
Hanako 90

If you want to sort in descending order, just set the sort method argument reverse to True as follows:

from operator import attrgetter
students.sort(key=attrgetter('score'), reverse=True)
for s in students:
    print(s.name, s.score)
Hanako 90
Jiro 80
Taro 70

Recommended Posts

[Python] How to sort instances by instance variables
[Python] How to sort instances by instance variables
[Python] How to sort dict in list and instance in list
How to access environment variables in Python
How to dynamically define variables in Python
How to install Python
How to sort by specifying a column in the Python Numpy array.
[python] How to sort by the Nth Mth element of a multidimensional array
[Python] How to expand variables in a character string
How to save a table scraped by python to csv
How to install Python [Windows]
python3: How to use bottle (2)
How to update Python Tkinter to 8.6
How to use Python argparse
Python class variables and instance variables
[Python] How to use checkio
How to define Go variables
How to run Notepad ++ Python
How to change Python version
How to develop in Python
[python] How to judge scalar
[Python] How to use input ()
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
Sort by date in python
How to use Python bytes
[Python] How to make a list of character strings character by character
How to switch the configuration file to be read by Python
[Python] How to play with class variables with decorator and metaclass
How to define multiple variables in a python for statement
How to override a user-defined method generated by python swig
How to install python using anaconda
How to write a Python class
[Python] How to do PCA in Python
[Python] Sort iterable by multiple conditions
[Python] How to derive nCk (ABC156-D)
[Python] How to use Pandas Series
How to collect images in Python
How to use Requests (Python Library)
How to use SQLite in Python
[Introduction to Python] How to parse JSON
How to get the Python version
How to get started with Python
[Python] How to import the library
[Python] How to use list 3 Added
How to use Mysql in python
How to use OpenPose's Python API
[Python] How to swap array values
How to wrap C in Python
How to use ChemSpider in Python
How to use FTP with Python
Python: How to use pydub (playback)
How to use PubChem in Python
How to speed up Python calculations
How to calculate date with python
How to access wikipedia from python
How to use python zip function
[Nanonets] How to post Memo [Python]
How to handle Japanese in Python