Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, sort a list by another list [duplicate]

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.

like image 203
dli Avatar asked Apr 14 '14 19:04

dli


3 Answers

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]])
like image 153
nneonneo Avatar answered Oct 18 '22 21:10

nneonneo


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

c = sorted(b, key = lambda e: a.index(e[0]))
like image 41
recursive Avatar answered Oct 18 '22 21:10

recursive


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']
like image 23
Christian Tapia Avatar answered Oct 18 '22 21:10

Christian Tapia