Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rearrange one list based on a second list of indices [duplicate]

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?

like image 750
Anis Souames Avatar asked Jan 09 '17 13:01

Anis Souames


1 Answers

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))] 
like image 123
OneCricketeer Avatar answered Oct 14 '22 10:10

OneCricketeer