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.
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']
You can do it using the key
named argument of sorted()
:
c = sorted(b, key = lambda e: a.index(e[0]))
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]])
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.
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']
You can do it using the key
named argument of sorted()
:
c = sorted(b, key = lambda e: a.index(e[0]))
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]])