I have a list of 10 items, and another list of 10 randomly not repeated numbers as following:
l = [a,b,c,d,e,f,g,h,i,j]
m = [1,4,5,9,2,6,3,7,8,10]
I want to rearrange l
, so that each item in l
takes its corresponding index from m
.
For example, b
should become the fourth and e
sould become the second.
I'm really stuck at the algorithm and the logic bugs me, so I don't have any idea on how to approach thi.
How can I do that?
If you're just trying to get elements moved around based on the other lists positions, you can loop over all elements of m
and grab that element of l
using list comprehension
l2 = [l[i - 1] for i in m]
But if you do want the ordering based on the other list, you're going to need to zip them together, sort on the index, then extract the elements
[y for x,y in sorted(zip(m,l))]
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