Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort list of tuples by reordering tuples

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;

like image 925
Vineet Avatar asked May 29 '14 02:05

Vineet


People also ask

How do you sort tuples of tuples?

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 ().

Can I sort a list of tuples?

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.

How do you sort a tuple to an order?

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.

How do you sort a list of tuples by second element in Python?

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.


1 Answers

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))
like image 188
kindall Avatar answered Sep 28 '22 05:09

kindall