Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting a list based on the order of another list

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading