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!