Will
Will

Reputation: 43

Sorting a list of list of tuples

I am trying to sort a list of 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 unable to reverse the order of the last element in the 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)]]

Soon I will be adding a 3rd value to the final tuple and sorting a third time. I am looking forward to your comments.

Upvotes: 3

Views: 142

Answers (2)

Konstantin
Konstantin

Reputation: 25329

You need to apply sorted two times.

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

sorted is guaranteed to be a stable sort, so we can use it in your case.

Demo

Upvotes: 3

Christian K.
Christian K.

Reputation: 2823

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

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

Upvotes: 2

Related Questions