5

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 the second element. List is like below.

L = [(1, 14, 0), (14, 1, 1), (1, 14, 2), (14, 2, 3), (2, 4, 4), (4, 11, 5), (11, -1000, 6)]

In C the sort function takes a compare function and that does everything simply. But I couldn't figure it out after trying for sometimes in python. Can anybody help me?

taufique
  • 2,701
  • 1
  • 26
  • 40
  • `sorted(L)` gives me `[(1, 14, 0), (1, 14, 2), (2, 4, 4), (4, 11, 5), (11, -1000, 6), (14, 1, 1), (14, 2, 3)]`. Is it a desired output? – alecxe Aug 22 '13 at 07:53
  • The order you want is called lexicographic order, and it's the default ordering for sequences, so you don't have to do anything special. – Bakuriu Aug 22 '13 at 08:01

1 Answers1

11

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.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I couldn't understand following part. sorted(L, key=lambda t: t[::-1]) Would you please explain a bit? – taufique Aug 22 '13 at 09:02
  • I previously tried in different way. Code snipet is here: http://paste.ubuntu.com/6013339/ But it was not working correctly. Where did I do wrong? – taufique Aug 22 '13 at 09:12
  • You defined `cmp_to_key()` twice, nested. The outer function doesn't return anything, so the result of that function is that you sort by `None` for each value; that leaves the original order unaffected. – Martijn Pieters Aug 22 '13 at 09:50
  • Remove the other function altogether. – Martijn Pieters Aug 22 '13 at 09:51
  • Ohh, My mistake. I just copied and pasted from net and pasted it mistakenly inside a function. :-P It is working now. – taufique Aug 22 '13 at 10:19