Sorting a list based on the order of another list

Question:

I have the following list:

I=[1,4, 3, 7,8,9]

I have another two lists which are subsets of list I:

IU=[3,9]
IUU=[4,8]

I have to merge lists IU and IUUto create list J in such a way that the elements of the merged list follow the orders of the elements of list I.

J=[4,3,8,9]

I am looking for some ideas on how to implement this. If I just add the sublist I get following result.

J=IU+IUU
J=[3, 9, 4, 8]

I will appreciate your comments/answers.

Asked By: mars

||

Answers:

I found the answer. Thanks for looking.

sorted(J,key=I.index)
Answered By: mars

You can just do something like:

sorted(IU + IUU, key={e:i for i,e in enumerate(I)}.get)

Which should be O(N*Log N)

The problem with key=I.index is that this will force your performance to deteriorate to O(N**2).

Answered By: juanpa.arrivillaga
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.