How to sort a python list by the order of matching values in another list

This is not an easy question to ask: I am talking about ordering list A by the order of matching values found in list B.

Most results talk about ordering list A by an ordering field in list B.

After some thinking, it became really obvious how to do this.

Simply create an empty list, find the index of an item in list A of list B.

list_a = [100, 1, 10]
list_b = [1, 10, 100]

sorted_list_b_by_list_a = sorted(list_a, key=lambda x: list_a.index(x))

3 Comments

  1. 丁銘顯 says:

    I think you make a mistake…
    In line 4:
    sorted_list_b_by_list_a = sorted(list_b, key=lambda x: list_a.index(x))
    ^^^^^^

  2. Hussan Rafiq says:

    Line 4 there is a mistake, replace list_a.index(x) with list_b.index(x)

Leave a reply to Hussan Rafiq Cancel reply