Home >Backend Development >Python Tutorial >How to Sort a List of Tuples with One Key in Reverse Order in Python?
Sorting a List with Two Keys, One in Reverse Order
In Python, sorting a list of tuples by two keys is straightforward. However, there may be cases where you need to sort one key in ascending order and another key in descending order.
Suppose you have a list with tuples like:
<code class="python">myList = [(ele1A, ele2A),(ele1B, ele2B),(ele1C, ele2C)]</code>
To sort this list using two keys, you can use sorted():
<code class="python">sortedList = sorted(myList, key=lambda y: (y[0].lower(), y[1]))</code>
This code sorts the list by the first key in ascending order and the second key in ascending order.
To sort the list in reverse order for one key, you can use a negative sign:
<code class="python">sortedList = sorted(myList, key=lambda y: (y[0].lower(), -y[1]))</code>
Here, the first key is still sorted in ascending order, but the second key is sorted in descending order.
You can try the following code snippets to see the different sorting results:
<code class="python">sortedList = sorted(myList, key=lambda y: (y[0].lower(), -y[1])) sortedList = sorted(myList, key=lambda y: (-y[0].lower(), y[1])) sortedList = sorted(myList, key=lambda y: (-y[0].lower(), -y[1]))</code>
The above is the detailed content of How to Sort a List of Tuples with One Key in Reverse Order in Python?. For more information, please follow other related articles on the PHP Chinese website!