Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list in python based on another sorted list

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

Is there a way to sort the list to reflect the presorted list despite the fact that not all the elements are present in the unsorted list?

I want the result to look something like this:

after_sort = ['2C','2D','3D','4D']

Thanks!

like image 235
Danica Fernandes Avatar asked Apr 09 '16 15:04

Danica Fernandes


1 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']
like image 135
unutbu Avatar answered Sep 28 '22 03:09

unutbu