Sort a list in python based on the position of its elements within another sorted list

Question:

I would like to sort a list in Python based on a pre-sorted list.

presorted_list = ['2C','3C','4C','2D','3D','4D']
unsorted_list = ['3D','2C','4D','2D']

How can I sort unsorted_list such that the values appear in the same order that presorted_list has them? That is, in this case the sorted result should be ['2C','2D','3D','4D'].

Asked By: Danica Fernandes

||

Answers:

In [5]: sorted(unsorted_list, key=presorted_list.index)
Out[5]: ['2C', '2D', '3D', '4D']

or, for better performance (particularly when len(presorted_list) is large),

In [6]: order = {item:i for i, item in enumerate(presorted_list)}    
In [7]: sorted(unsorted_list, key=order.__getitem__)
Out[7]: ['2C', '2D', '3D', '4D']

For more on how to sort using keys, see the excellent Howto Sort wiki.


If unsorted_list contains items (such as '6D') not in presorted_list then the above methods will raise an error. You first have to decide how you want to sort these items. If you want them placed at the end of the list, you could use

In [10]: unsorted_list = ['3D','2C','6D','4D','2D']

In [11]: sorted(unsorted_list, key=lambda x: order.get(x, float('inf')))
Out[11]: ['2C', '2D', '3D', '4D', '6D']

or if you wish to place such items at the front of the list, use

In [12]: sorted(unsorted_list, key=lambda x: order.get(x, -1))
Out[12]: ['6D', '2C', '2D', '3D', '4D']
Answered By: unutbu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.