Home > Backend Development > Python Tutorial > How to Sort Lists of Lists in Alternating Order in Python?

How to Sort Lists of Lists in Alternating Order in Python?

Susan Sarandon
Release: 2024-10-21 16:56:02
Original
432 people have browsed it

How to Sort Lists of Lists in Alternating Order in Python?

Sorting Lists of Lists in Alternating Order

Given a list containing sublists in the format [['a',1], ['a',2], ['a',3], ['b',1], ['b',2], ['b',3]], the goal is to sort these sublists in an alternating manner, with element 0 sorted in descending order and element 1 sorted in ascending order. The expected result is [['b',1], ['b',2], ['b',3], ['a',1], ['a',2], ['a',3]].

To achieve this, one can leverage the sort() function with a custom key. The key is a lambda function that extracts the elements of interest and applies a sort operation to them. In this case, it retrieves the first element of each sublist, applies descending sort, and then combines it with the negative of the second element, sorted in ascending order. By reversing the sort order with reverse=True, the sublists are sorted descending by the first element and ascending by the second element. This results in the desired alternating order.

The following code snippet demonstrates the 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)

print(L)
# [['b', 1], ['b', 2], ['b', 3], ['a', 1], ['a', 2], ['a', 3]]</code>
Copy after login

The above is the detailed content of How to Sort Lists of Lists in Alternating Order 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