Python, sort a list by another list

Question:

I have a list a:

a = ['c','d','b','a','e']

and a list b:

b = ['a001','b002','c003','d004','e005']

and how could I get my list c as following:

c = ['c003','d004','b002','a001','e005']

Basically sort b using part of each element, by the order defined in a.

Many Thanks.

Asked By: dli

||

Answers:

You can try passing a lambda function to the key parameter of the sorted() built-in function:

a = ['c', 'd', 'B', 'a', 'e']
b = ['a001', 'B002', 'c003', 'd004', 'e005']
c = sorted(b, key = lambda x: a.index(x[0])) # ['c003', 'd004', 'b002', 'a001', 'e005']
Answered By: Christian Tapia

You can do it using the key named argument of sorted():

c = sorted(b, key = lambda e: a.index(e[0]))
Answered By: recursive

If you have a very big list, the solutions using .index will not be very efficient as the first list will be index‘d for each entry in the second list. This will take O(n^2) time.

Instead, you can construct a sort mapping:

order = {v:i for i,v in enumerate(a)}
c = sorted(b, key=lambda x: order[x[0]])
Answered By: nneonneo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.