Sort tuple list in Python by specifying the ascending / descending order of multiple keys

Thing you want to do

When sorting by SQL

Select * from table Order By key1 DESC, key2 ASC

You can specify the ascending / descending order of each key as in.

In C / C ++ etc., you can do the same by defining the comparison function yourself.

int compare(const MyStruct *a, const MyStruct *b)
{
    if(a->k1 == b->k1){
        return b->k2 - a->k2;
    }else{
        return a->k1 - b->k2;
    }
}

On the other hand, in Python, sort can only specify the key function and the overall ascending / descending order, so what should we do if we sort tuples with multiple elements in this way?

Solution

It was written in the official doc. https://docs.python.org/3/howto/sorting.html#sort-stability-and-complex-sorts

Sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.

This wonderful property lets you build complex sorts in a series of sorting steps. For example, to sort the student data by descending grade and then ascending age, do the age sort first and then sort again using grade

def multisort(xs, specs):
    for key, reverse in reversed(specs):
        xs.sort(key=lambda x: x[key], reverse=reverse)
    return xs

Since Python sorting is a stable sorting, you can sort repeatedly by specifying the ascending / descending order in order from the key with the lowest priority. I see!!

Recommended Posts

Sort tuple list in Python by specifying the ascending / descending order of multiple keys
[python] Get the rank of the values in List in ascending / descending order
When specifying multiple keys in python sort
[Python] Sort the list of pathlib.Path in natural sort
Python> Get a list of files in multiple directories> Use glob | Sort by modification time
Sort the file names obtained by Python glob in numerical order
Sort of tuple array can be accelerated by specifying key (Python)
I want to sort a list in the order of other lists
How to sort by specifying a column in the Python Numpy array.
Sort the elements of the array by specifying the conditions
Make a copy of the list in Python
Search by the value of the instance in the list
Sort list elements in a specified order in Python
[python] Get the list of classes defined in the module
[Python] Outputs all combinations of elements in the list
Group by consecutive elements of a list in Python
[Python] How to output the list values in order
Sort files updated within the period specified by the find command in order of size
python in mongodb in descending sort
Sort by date in python
Sort and output the elements in the list as elements and multiples in Python.
Implemented the algorithm of "Algorithm Picture Book" in Python3 (Bubble Sort)
Get the number of specific elements in a python list
Sort the string array in order of length & Japanese syllabary
[Python3] Call by dynamically specifying the keyword argument of the function
Implemented the algorithm of "Algorithm Picture Book" in Python3 (selection sort)
Extract multiple list duplicates in Python
[Python] Sort iterable by multiple conditions
[Python] Display only the elements of the list side by side [Vertical, horizontal]
[Understanding in the figure] Management of Python virtual environment by Pipenv
Read the standard output of a subprocess line by line in Python
Delete multiple elements in python list
Sort by specifying conditions in CASTable
About the basics list of Python basics
Extension of Python by C or C ++ (when there are multiple arguments, when passing a list from the Python side)
[Introduction to Python] How to sort the contents of a list efficiently with list sort
Receive a list of the results of parallel processing in Python with starmap
Check the behavior of destructor in Python
Display a list of alphabets in Python 3
OR the List in Python (zip function)
The result of installing python in Anaconda
Read the file line by line in Python
Read the file line by line in Python
The basics of running NoxPlayer in Python
Pandas of the beginner, by the beginner, for the beginner [Python]
Basic grammar of Python3 series (list, tuple)
Summary of built-in methods in Python list
In search of the fastest FizzBuzz in Python
Get the EDINET code list in Python
How to pass the execution result of a shell command in a list in Python
[Python] Precautions when retrieving data by scraping and putting it in the list
plot the coordinates of the processing (python) list and specify the number of times in draw ()
Divides the character string by the specified number of characters. In Ruby and Python.
Execution order when multiple context managers are specified in the Python with statement
Get Unix time of the time specified by JST regardless of the time zone of the server in Python
[python] How to sort by the Nth Mth element of a multidimensional array
Extract elements (using a list of indexes) in a NumPy style from a Python list / tuple
Get the last element of the array by splitting the string in Python and PHP
How to get a list of files in the same directory with python
Output the number of CPU cores in Python
[python] Check the elements of the list all, any