Sorting HOW TO¶
Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable.
In this document, we explore the various techniques for sorting data using Python.
Sorting Basics¶
A simple ascending sort is very easy: just call the sorted() function. It returns a new sorted list:
You can also use the list.sort() method. It modifies the list in-place (and returns None to avoid confusion). Usually it’s less convenient than sorted() — but if you don’t need the original list, it’s slightly more efficient.
Another difference is that the list.sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable.
Key Functions¶
Both list.sort() and sorted() have a key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons.
For example, here’s a case-insensitive string comparison:
The value of the key parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
A common pattern is to sort complex objects using some of the object’s indices as keys. For example:
The same technique works for objects with named attributes. For example:
Operator Module Functions¶
The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The operator module has itemgetter() , attrgetter() , and a methodcaller() function.
Using those functions, the above examples become simpler and faster:
The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age:
Ascending and Descending¶
Both list.sort() and sorted() accept a reverse parameter with a boolean value. This is used to flag descending sorts. For example, to get the student data in reverse age order:
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.
Notice how the two records for blue retain their original order so that (‘blue’, 1) is guaranteed to precede (‘blue’, 2) .
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:
This can be abstracted out into a wrapper function that can take a list and tuples of field and order to sort them on multiple passes.
The Timsort algorithm used in Python does multiple sorts efficiently because it can take advantage of any ordering already present in a dataset.
The Old Way Using Decorate-Sort-Undecorate¶
This idiom is called Decorate-Sort-Undecorate after its three steps:
First, the initial list is decorated with new values that control the sort order.
Second, the decorated list is sorted.
Finally, the decorations are removed, creating a list that contains only the initial values in the new order.
For example, to sort the student data by grade using the DSU approach:
This idiom works because tuples are compared lexicographically; the first items are compared; if they are the same then the second items are compared, and so on.
It is not strictly necessary in all cases to include the index i in the decorated list, but including it gives two benefits:
The sort is stable – if two items have the same key, their order will be preserved in the sorted list.
The original items do not have to be comparable because the ordering of the decorated tuples will be determined by at most the first two items. So for example the original list could contain complex numbers which cannot be sorted directly.
Another name for this idiom is Schwartzian transform, after Randal L. Schwartz, who popularized it among Perl programmers.
Now that Python sorting provides key-functions, this technique is not often needed.
The Old Way Using the cmp Parameter¶
Many constructs given in this HOWTO assume Python 2.4 or later. Before that, there was no sorted() builtin and list.sort() took no keyword arguments. Instead, all of the Py2.x versions supported a cmp parameter to handle user specified comparison functions.
In Py3.0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__() magic method).
In Py2.x, sort allowed an optional function which can be called for doing the comparisons. That function should take two arguments to be compared and then return a negative value for less-than, return zero if they are equal, or return a positive value for greater-than. For example, we can do:
Or you can reverse the order of comparison with:
When porting code from Python 2.x to 3.x, the situation can arise when you have the user supplying a comparison function and you need to convert that to a key function. The following wrapper makes that easy to do:
To convert to a key function, just wrap the old comparison function:
In Python 3.2, the functools.cmp_to_key() function was added to the functools module in the standard library.
Odd and Ends¶
For locale aware sorting, use locale.strxfrm() for a key function or locale.strcoll() for a comparison function.
The reverse parameter still maintains sort stability (so that records with equal keys retain the original order). Interestingly, that effect can be simulated without the parameter by using the builtin reversed() function twice:
The sort routines use < when making comparisons between two objects. So, it is easy to add a standard sort order to a class by defining an __lt__() method:
However, note that < can fall back to using __gt__() if __lt__() is not implemented (see object.__lt__() ).
Key functions need not depend directly on the objects being sorted. A key function can also access external resources. For instance, if the student grades are stored in a dictionary, they can be used to sort a separate list of student names:
Функция sorted¶
Функция sorted возвращает новый отсортированный список, который получен из итерируемого объекта, который был передан как аргумент. Функция также поддерживает дополнительные параметры, которые позволяют управлять сортировкой.
Первый аспект, на который важно обратить внимание — sorted всегда возвращает список.
Если сортировать список элементов, то возвращается новый список:
При сортировке кортежа также возвращается список:
Если передать sorted словарь, функция вернет отсортированный список ключей:
reverse¶
Флаг reverse позволяет управлять порядком сортировки. По умолчанию сортировка будет по возрастанию элементов.
Указав флаг reverse, можно поменять порядок:
С помощью параметра key можно указывать, как именно выполнять сортировку. Параметр key ожидает функцию, с помощью которой должно быть выполнено сравнение.
Например, таким образом можно отсортировать список строк по длине строки:
Если нужно отсортировать ключи словаря, но при этом игнорировать регистр строк:
Параметру key можно передавать любые функции, не только встроенные. Также тут удобно использовать анонимную функцию lambda.
С помощью параметра key можно сортировать объекты не по первому элементу, а по любому другому. Но для этого надо использовать или функцию lambda, или специальные функции из модуля operator.
Например, чтобы отсортировать список кортежей из двух элементов по второму элементу, надо использовать такой прием:
Пример сортировки разных объектов¶
Сортировка выполняется по первому элементу, например, по первому символу в списке строк, если он одинаковый, по второму и так далее. Сортировка выполняется по коду Unicode символа. Для символов из одного алфавита, это значит что сортировка по сути будет по алфавиту.
Пример сортировки списка строк:
Некоторые данные будут сортироваться неправильно, например, список IP-адресов:
Это происходит потому используется лексикографическая сортировка. Чтобы в данном случае сортировка была нормальной, надо или использовать отдельный модуль с натуральной сортировкой (модуль natsort) или сортировать, например, по двоичному/десятичному значению адреса.
Пример сортировки IP-адресов по двоичному значению. Сначала создаем функцию, которая преобразует IP-адреса в двоичный формат:
Сортировка с использованием функции bin_ip:
Также дальше будет рассматриваться модуль ipaddress, который позволит создавать специальные объекты, которые соответствуют IP-адресу и они уже сортируются правильно по десятичному значению.
Функция sorted() в Python
Функция sorted() в Python возвращает отсортированный список из элементов в итерируемом объекте.
Команда сортирует элементы данной итерации в определенном порядке (по возрастанию или убыванию) и возвращает отсортированную итерацию в виде списка.
Параметры функции
Метод может принимать не более трех параметров:
- iterable ‒ последовательность (строка, кортеж, список) или коллекция (набор, словарь, замороженный набор) или любой другой итератор.
- reverse (необязательно) ‒ если True, отсортированный список переворачивается (или сортируется в порядке убывания). Если не указано иное, по умолчанию используется значение False.
- key (необязательно) ‒ функция, которая служит ключом для сравнения сортировки. По умолчанию Нет.
Пример 1: Сортировка строки, списка и кортежа
Обратите внимание, что во всех случаях возвращается отсортированный список.
Примечание: В списке также есть метод sort(), который работает так же, как sorted(). Единственное отличие состоит в том, что метод sort() не возвращает никакого значения и изменяет исходный список.
Пример 2: Сортировка по убыванию
Функция sorted() принимает обратный параметр в качестве необязательного аргумента.
Установка reverse = True сортирует итерацию в порядке убывания.
Ключевой параметр
Если нужна собственная реализация для сортировки, sorted() также принимает ключевую функцию в качестве необязательного параметра.
На основе возвращенного значения ключевой функции вы можете отсортировать данную итерацию.
Список сортируется по длине элемента от наименьшего количества к наибольшему.
Пример 3: Сортировка списка с ключевой функцией
Пример 4: Сортировка с использованием нескольких ключей
Допустим, у нас есть следующий список:
Отсортировать список нужно таким образом, чтобы ученик с самыми высокими оценками был в начале. Если ученики имеют одинаковые оценки, их необходимо отсортировать так, чтобы младший участник был первым.
Мы можем добиться этого типа сортировки с несколькими ключами, возвращая кортеж вместо числа.
Два кортежа можно сравнить, вместе с их элементами, начиная с первого. Если есть связь (элементы равны), сравнивается второй элемент и так далее.
Воспользуемся этой логикой для сортировки:
Поскольку логическая функция сортировки мала и умещается в одну строку, лямбда-функция используется внутри ключа, а не передает отдельное имя функции.
Вышеупомянутая программа может быть написана с использованием лямбда-функции следующим образом: