Sorting a list of a list of tuples

I am trying to sort a list of a list of tuples based on the values ​​in the last tuple.

[[(3, 1005), (3, 1050), (3, 945), (4, 1510), (13, 4510)],
[(3, 1000), (3, 955), (4, 1501), (5, 1900), (15, 5356)],
[(3, 945), (3, 955), (3, 901), (5, 1900), (14, 4701)],
[(3, 1000), (3, 945), (3, 901), (5, 1900), (14, 4746)],
[(3, 1000), (3, 1050), (3, 955), (4, 1500), (13, 4505)],
[(3, 1050), (3, 955), (4, 1511), (5, 1905), (15, 5421)]]

      

Specifically, I want the final tuples to be sorted in ascending order by the first element and in descending order by the second element.

I was able to sort the last tuple using this code:

validCombo = sorted(validCombo, key=operator.itemgetter(4))

      

BUT cannot change the order of the last element in a tuple. I need the following output:

[[(3, 1005), (3, 1050), (3, 945), (4, 1510), (13, 4510)],
[(3, 1000), (3, 1050), (3, 955), (4, 1500), (13, 4505)],
[(3, 1000), (3, 945), (3, 901), (5, 1900), (14, 4746)],
[(3, 945), (3, 955), (3, 901), (5, 1900), (14, 4701)],
[(3, 1050), (3, 955), (4, 1511), (5, 1905), (15, 5421)],
[(3, 1000), (3, 955), (4, 1501), (5, 1900), (15, 5356)]]

      

I will soon add a third value to the last tuple and sort it a third time. I look forward to your comments.

+3


source to share


2 answers


You need to apply it sorted

twice.

validCombo = sorted(validCombo, key=lambda elem: elem[numDays][1], reverse = True)
validCombo = sorted(validCombo, key=lambda elem: elem[numDays][0])

      



sorted

a stable assortment is guaranteed , so we can use it in your case.

Demo

+3


source


You can make the combined key of both elements of the tuple:



sorted(data, key=lambda q: (q[4][0],-q[4][1]))

      

+2


source







All Articles