I have a list of some tuples. Each tuple has three elements. I need to sort the list. To break tie between two tuples, first element of tuple is looked then if still tied then t
Just sort the list; the default sort does just what you want.
When comparing two tuples, they are ordered according to their contents; sorted on the first element first, then if they are equal, sorted on the second element, etc.
Demo:
>>> L = [(14, 2, 3), (1, 14, 0), (14, 1, 1), (1, 14, 2), (2, 4, 4), (4, 11, 5), (11, -1000, 6)]
>>> sorted(L)
[(1, 14, 0), (1, 14, 2), (2, 4, 4), (4, 11, 5), (11, -1000, 6), (14, 1, 1), (14, 2, 3)]
I moved the (14, 2, 3)
element forward to show that it is still sorted after (14, 1, 1)
.
Python's list.sort()
method and sorted()
function take a key
function that returns a value on which to sort instead if you need a different sort order. If you wanted to sort on the last element first, then second last, etc. for example, you'd use:
sorted(L, key=lambda t: t[::-1])
where the lambda returns a reversed tuple to sort on instead. The callable object you pass to key
is called for each element in the input sequence to 'augment' the list before sorting, as if you had done:
[s[1] for s in sorted((key(s), s) for s in L)]
The t[::-1]
uses a reversing slice.
For more detail, see the Python Sorting HOWTO.