Sorting a Nested List with Descending and Ascending Elements
In Python, you can encounter scenarios where you need to sort a list containing nested lists with specific sorting criteria. Consider a list like this:
['a',1] ['a',2] ['a',3] ['b',1] ['b',2] ['b',3]
The task is to sort this list so that element 0 (the letter) is sorted in descending order, while element 1 (the number) is sorted in ascending order. The resulting list should look like:
['b',1] ['b',2] ['b',3] ['a',1] ['a',2] ['a',3]
To achieve this sorting, we can employ Python's built-in sort function along with a custom key function that sorts based on multiple criteria. The key function will take each nested list as input and generate a tuple that serves as the sorting key.
The following code snippet demonstrates how to sort the nested list using the custom key 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>
In this code, the key function generates a tuple using the first element (letter) and the negation of the second element (number). Negating the second element allows us to accomplish the ascending sort for numbers. The additional reverse=True argument in the sort function ensures descending sorting based on the tuple key.
As a result, the list L will now be sorted as desired:
[['b', 1], ['b', 2], ['b', 3], ['a', 1], ['a', 2], ['a', 3]]
This approach provides a versatile way to sort complex data structures like nested lists with multiple sorting criteria.
The above is the detailed content of How to Sort a Nested List with Descending and Ascending Elements in Python?. For more information, please follow other related articles on the PHP Chinese website!