sort list of tuples by reordering tuples
performance, python, sorting, tuples
Solution
Using `operator.itemgetter` for your `key` function may be faster; you'd have to try it.
import operator
sorted(A, key=operator.itemgetter(2, 0, 1))
Problem
Given a list of tuples to sort, python will sort them according to first element in tuple, then second element and so on. ``` >>> A [(3, 2, 1), (0, 3, 0), (2, 1, 0), (2, 2, 3), (0, 3, 2), (2, 1, 1), (3, 3, 2), (3, 2, 0)] >>> sorted(A) [(0, 3, 0), (0, 3, 2), (2, 1, 0), (2, 1, 1), (2, 2, 3), (3, 2, 0), (3, 2, 1), (3, 3, 2)] ``` This works great. Now I want to sort them by third element, then first element and then the second element which I can do by either providing a key function or a cmp function. ``` >>> A [(3, 2, 1), (0, 3, 0), (2, 1, 0), (2, 2, 3), (0, 3, 2), (2, 1, 1), (3, 3, 2), (3, 2, 0)] >>> sorted(A, key = lambda x: (x[2], x[0], x[1])) [(0, 3, 0), (2, 1, 0), (3, 2, 0), (2, 1, 1), (3, 2, 1), (0, 3, 2), (3, 3, 2), (2, 2, 3)] ``` except i take a major performance penalty ``` s ="""\ from numpy.random import randint as rr A=[tuple(rr(0,10,3)) for i in range(100)] def tuplecmp(t1, t2): return t1[0] - t2[0] """ c1 = """\ sorted(A) """ c2 = """\ sorted(A, key=lambda x: (x[2], x[0], x[1])) """ c3 = """\ sorted(A, cmp = tuplecmp) """ import timeit print timeit.timeit(c1,number=10000, setup= s) print timeit.timeit(c2,number=10000, setup= s) print timeit.timeit(c3,number=10000, setup= s) ``` giving ``` 0.60133600235, 0.980231046677, 2.68837809563 ``` Further, the order in which I compare the individual tuple elements need not remain same. I may need to compare by 'second, first, then third' element etc. Is there a better method to do provide arbitrary comparator functions without a major performance penalty;