Wednesday, February 21, 2018

Sorting a list based on values from another list


Let’s consider the following two lists…

X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]

Now we would like to sort the list X based on the list Y. The final sorted list X would look like the following…

["a", "d", "h", "b", "c", "e", "i", "f", "g"]

Solution…
  1. ·  zip the two lists.
  2. ·  create a new, sorted list based on the zip using sorted().
  3. ·  using a list comprehension extract the first elements of each pair from the sorted, zipped list.


[x for _, x in sorted(zip(Y,X), key=lambda pair: pair[0])]