Home  >  Article  >  Backend Development  >  How to Sort a Nested List with Descending and Ascending Elements in Python?

How to Sort a Nested List with Descending and Ascending Elements in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-10-21 16:41:02543browse

How to Sort a Nested List with Descending and Ascending Elements in Python?

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!

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