Home > Backend Development > Python Tutorial > How to Sort a List of Lists in Descending and Ascending Order?

How to Sort a List of Lists in Descending and Ascending Order?

Patricia Arquette
Release: 2024-10-21 17:24:02
Original
613 people have browsed it

How to Sort a List of Lists in Descending and Ascending Order?

Sorting a List of Lists in Descending and Ascending Order

Given a list of lists with two elements, the goal is to sort the lists first in descending order based on the first element, and then in ascending order based on the second element.

To achieve this, we can utilize the sort() method along with a custom key function. Here's a solution:

<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

The key argument of the sort() method specifies a function that determines the sorting order. In this case, we define a lambda function that takes a list k and returns a tuple. The first element of the tuple is the first element of the list k[0], which is used for descending sorting. The second element is the negation of the second element of the list -k[1], which is used for ascending sorting.

By sorting in descending order first, reverse=True ensures that the first element of each list ('a' or 'b') is sorted in reverse alphabetical order. Subsequently, the ascending sorting of the second element results in an overall list sorted as:

[['b', 1], ['b', 2], ['b', 3], ['a', 1], ['a', 2], ['a', 3]]
Copy after login

This effectively achieves the desired sorting criterion.

The above is the detailed content of How to Sort a List of Lists in Descending and Ascending Order?. 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