Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting list of tuples by arbitrary key

Tags:

python

order = ['w','x','a','z']
[(object,'a'),(object,'x'),(object,'z'),(object,'a'),(object,'w')]

How do I sort the above list of tuples by the second element according the the key list provided by 'order'?

UPDATE on 11/18/13:

I found a much better approach to a variation of this question where the keys are certain to be unique, detailed in this question: Python: using a dict to speed sorting of a list of tuples.

My above question doesn't quite apply because the give list of tuples has two tuples with the key value of 'a'.

like image 663
Cole Avatar asked Nov 16 '12 01:11

Cole


People also ask

How do you 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. Unfortunately, Python does not allow you to specify the index of the sorting element directly.

How do you sort the list of tuples by value?

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. Copied!

How do you sort tuples of tuples?

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

How do you sort a tuple in Python without sorting?

You can use one of the easiest sorting algorithm that is bubble sort. In case of tuples in tuple it will sort in order of first element of tuple. So ((32, "b"), (1, "c"), (23,"a")) Now if you sort it it will sort it in the order of 1st element of tuple.


1 Answers

You can use sorted, and give as the key a function that returns the index of the second value of each tuple in the order list.

>>> sorted(mylist,key=lambda x: order.index(x[1]))

[('object', 'w'), ('object', 'x'), ('object', 'a'), ('object', 'a'), ('object', 'z')]

Beware, this fails whenever a value from the tuples is not present within the order list.

Edit:

In order to be a little more secure, you could use :

sorted(mylist,key=lambda x: x[1] in order and order.index(x[1]) or len(order)+1)

This will put all entries with a key that is missing from order list at the end of the resulting list.

like image 189
Julien Vivenot Avatar answered Nov 06 '22 09:11

Julien Vivenot