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

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

Susan Sarandon
Susan SarandonOriginal
2024-10-21 16:56:02347browse

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>

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!

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