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;
In Python, use the sorted() built-in function to sort a Tuple. The tuple should be passed as an argument to the sorted() function. The tuple items are sorted (by default) in ascending order in the list returned by the function. We can use a tuple to convert this list data type to a tuple ().
If you specifically want to sort a list of tuples by a given element, you can use the sort() method and specify a lambda function as a key.
To sort a Tuple in Python, use sorted() builtin function. Pass the tuple as argument to sorted() function. The function returns a list with the items of tuple sorted in ascending order.
Use the key argument of the sorted() function to sort a list of tuples by the second element, e.g. sorted_list = sorted(list_of_tuples, key=lambda t: t[1]) . The function will return a new list, sorted by the second tuple element.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With