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

Linda Hamilton
Release: 2024-10-21 16:41:02
Original
536 people have browsed it

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]
Copy after login

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]
Copy after login

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>
Copy after login

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]]
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!