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.
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]])
You can do it using the key
named argument of sorted()
:
c = sorted(b, key = lambda e: a.index(e[0]))
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With