Note: I'm assuming that m
is always contiguous (i.e. there are no "gaps"), and starts at 1
.
If so, you can get what you want quite easily, using a list comprehension, zip()
and sorted()
.
Let's take it step by step:
>>> l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
>>> m = [1, 4, 5, 9, 2, 6, 3, 7, 8, 10]
zip()
pairs each element of m
with an element of l
:
>>> zip(m, l)
[(1, 'a'), (4, 'b'), (5, 'c'), (9, 'd'), (2, 'e'), (6, 'f'), (3, 'g'), (7, 'h'), (8, 'i'), (10, 'j')]
sorted()
returns a sorted copy of the list of pairs:
>>> sorted(zip(m, l))
[(1, 'a'), (2, 'e'), (3, 'g'), (4, 'b'), (5, 'c'), (6, 'f'), (7, 'h'), (8, 'i'), (9, 'd'), (10, 'j')]
Finally, a list comprehension takes just the second item from each pair:
>>> [x for i, x in sorted(zip(m, l))]
['a', 'e', 'g', 'b', 'c', 'f', 'h', 'i', 'd', 'j']