Home  >  Article  >  Backend Development  >  How to Sort Lists With Multiple Keys, Including Reverse Ordering in Python?

How to Sort Lists With Multiple Keys, Including Reverse Ordering in Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 05:58:03723browse

How to Sort Lists With Multiple Keys, Including Reverse Ordering in Python?

Sorting Lists with Multiple Keys, Including Reverse Ordering

Python provides the sorted() function for sorting lists. To sort by multiple keys, a lambda function can be used as the key argument. However, when sorting with multiple keys, all keys are sorted in ascending order by default.

Consider a list of tuples:

<code class="python">myList = [(ele1A, ele2A), (ele1B, ele2B), (ele1C, ele2C)]</code>

To sort this list using both keys, the following code can be used:

<code class="python">sortedList = sorted(myList, key=lambda y: (y[0].lower(), y[1]))</code>

This code sorts the elements in ascending order by the first key and then by the second key in ascending order. To sort in reverse order with one key, the lambda function can be modified:

<code class="python">sortedList = sorted(myList, key=lambda y: (y[0].lower(), -y[1]))</code>

In this example, the negative sign before y[1] reverses the sorting order for the second key. However, this code will sort all elements in reverse order by the second key.

To sort in reverse order by one key and ascending order by the other, the following code can be used:

<code class="python">sortedList = sorted(myList, key=lambda y: (-y[0].lower(), y[1]))</code>

Here, the negative sign is used with the first key to reverse the sorting order for the first key.

The above is the detailed content of How to Sort Lists With Multiple Keys, Including Reverse Ordering in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn