Multiple requirements while sorting a list of tuples

Viewed 63

I have a list of tuples, namely [(7, 14), (3, 12), (20, 22), (6, 14), (2, 12)]. I want to sort it by the second value in the tuple, but if the second values are the same, I want the earlier element in a sorted list to be with the lower first value. For more clarity (6,14) should be earlier in the sorted list, then (7, 14).

Right now I have the following code:

result = [(7, 14), (3, 12), (20, 22), (6, 14), (2, 12)]
result.sort(key = lambda a: a[1])
Output[]: [(3, 12), (2, 12), (7, 14), (6, 14), (20, 22)]

What I want is:

Output[]: [(2, 12), (3, 12), (6, 14), (7, 14), (20, 22)]
3 Answers

Sort as if the elements of the tuples were reversed.

>>> ts = [(7, 14), (3, 12), (20, 22), (6, 14), (2, 12)]
>>> ts.sort(key=lambda t: t[::-1])
>>> ts
[(2, 12), (3, 12), (6, 14), (7, 14), (20, 22)]

sort and sorted sort lexicographically by default, which means that if the first element of whatever is sorted matches, then it looks at the second element, and so on.

lambda t: (t[1], t[0]) would also have worked.

You could also use itemgetter in place of a lambda:

from operator import itemgetter
result = [(7, 14), (3, 12), (20, 22), (6, 14), (2, 12)]

print(sorted(result, key=itemgetter(1, 0)))

Output:

[(2, 12), (3, 12), (6, 14), (7, 14), (20, 22)]

You can try this:-

result = sorted(result, key=lambda k :(k[1], k[0]))
print(result)

Output:-

[(2, 12), (3, 12), (6, 14), (7, 14), (20, 22)]
Related