Home > Blockchain >  Sorting a short list according to the order of a longer list
Sorting a short list according to the order of a longer list

Time:11-24

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:

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

CodePudding user response:

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']
  • Related