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

Linda Hamilton
Release: 2024-10-21 16:42:02
Original
975 people have browsed it

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

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]).

  • k[0] is the first element of the sublist, which we want to sort in descending order.
  • -k[1] is the negative of the second element, which we want to sort in ascending order. By inverting the sign, we achieve ascending order.

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

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!

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!