How to sort a list of tuples according to another list
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]
Another posibility is to sort a
, sort the indices of b
according to b
and than sort the a
according to the indices
a.sort(key=lambda x: x[0])
ind = [i[0] for i in sorted(enumerate(b),key=lambda x: x[1])]
a = [i[0] for i in sorted(zip(a,ind),key=lambda x: x[1])]
since every sorting takes n*log(n) this is still scalable for bigger lists