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 short list according to the order of a longer list

Suppose I have a reference list:

A = ['X_0', 'Z_0', 'X_1', 'Y_0', 'Z_1', 'X_2', 'Y_1', 'Z_2', 'Y_2']

as well as an (example) shorter list:

B = ['Z_0', 'X_1', 'X_0']

How can I sort B so that the order of the elements match the order provided in A? The final results should thus match the order of A like so:

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

B_final = ['X_0', 'Z_0', 'X_1']

>Solution :

You want the list B sorted by the index of the value in A, so;

sorted(B, key=A.index)

This will sort B by each values index in A.

If you are using a very long list, index is not very efficient since it searches the list for every value, so you may want to go for sorting by a dictionary instead.

First create a dictionary of the index values of the list;

>>> C = {val:ix for ix,val in enumerate(A)}

…then sort by the dictionary value, which is much more efficient than a linear search in the list;

>>> sorted(B, key=C.get)
['X_0', 'Z_0', 'X_1']
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