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

One thought on “How to sort a python list by the order of matching values in another list

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s