Given a list l0
of numbers in arbitrary order that may contain duplicates, how to have it sorted to l_s
while keeping track of how l0
was sorted, so that the original l0_order
can be reproduced later on (l_in_l0_order
)?
The point is to apply l0_order
to another list l
that is in l_s
order to retrieve a list l_in_l0_order
ordered according to l0
.
What I use so far is
l0 = [1, 7, 3, 12, 12, 4]
ls = sorted(l0)
# ls
# [1, 3, 4, 7, 12, 12]
l0_order = [ls.index(v) for v in l0]
l_in_l0_order = [ls[i] for i in l0_order]
# l_in_l0_order
# [1, 7, 3, 12, 12, 4]
- is there a more clever way to do this? For large lists, this make a lot of calls to
index
Note: for a list with elements with equal value but different id
, the method above can produce invalid results because index
(afaik) compares values, not ids. I do not require that behavior (order of id
), but it might be of relevance for a general solution.