Home > Article > Backend Development > How to Sort a Nested List Ascending and Descending in Python?
How to Sort a Nested List in Ascending and Descending Order
In Python, you can encounter situations where you have a list that contains sublists, and you need to sort them in a specific way, such as sorting the first element in descending order and the second element in ascending order.
To achieve this, you can utilize the key argument in the sort() function. This argument allows you to specify how the elements should be compared for sorting. In this case, we need a custom sorting function:
<code class="python">L = [['a', 1], ['a', 2], ['a', 3], ['b', 1], ['b', 2], ['b', 3]] L.sort(key=lambda k: (k[0], -k[1]), reverse=True)</code>
The key argument takes a lambda function as its value. This function receives an element k representing a sublist, and returns a tuple: (k[0], -k[1]).
By specifying reverse=True, we sort the resulting list in descending order based on the tuples returned by the lambda function.
As a result, the L list now contains:
<code class="python">[['b', 1], ['b', 2], ['b', 3], ['a', 1], ['a', 2], ['a', 3]]</code>
This demonstration showcases how to effectively sort a nested list using a custom sorting function based on the key argument in the sort() function.
The above is the detailed content of How to Sort a Nested List Ascending and Descending in Python?. For more information, please follow other related articles on the PHP Chinese website!