Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list of tuples according to another list

There is a list:

a = [("ax", 1), ("ec", 3), ("bk", 5)] 

another list:

b = ["ec", "ax", "bk"] 

I want to sort a according to b:

sort_it(a, b)  a = [("ec", 3), ("ax", 1), ("bk", 5)] 

How to do this?

like image 671
alwbtc Avatar asked Oct 10 '12 08:10

alwbtc


People also ask

How do you sort the list of tuples by the second element?

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.

How do you sort two tuples in Python?

Sorting a List by the Second Element of the 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. Unfortunately, Python does not allow you to specify the index of the sorting element directly.

How do you sort a list of tuples in Python using lambda?

The list. sort() method key parameter is set to lambda. The arguement x is the iterable element ( tuple ) to be sorted by the second element, the number. The lambda expression sorts the list by the second element of the tuple value and updates the original.


1 Answers

a.sort(key=lambda x: b.index(x[0])) 

This sorts a in-place using the the index in b of the first element of each tuple from a as the values it sorts on.

Another, possibly cleaner, way of writing it would be:

a.sort(key=lambda (x,y): b.index(x)) 

If you had large numbers of items, it might be more efficient to do things a bit differently, because .index() can be an expensive operation on a long list, and you don't actually need to do a full sorting since you already know the order:

mapping = dict(a) a[:] = [(x,mapping[x]) for x in b] 

Note that this will only work for a list of 2-tuples. If you want it to work for arbitrary-length tuples, you'd need to modify it slightly:

mapping = dict((x[0], x[1:]) for x in a) a[:] = [(x,) + mapping[x] for x in b] 
like image 132
Amber Avatar answered Sep 24 '22 08:09

Amber