Sort a list in python based on another sorted list

丶灬走出姿态 提交于 2020-03-13 07:55:38

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/36518800/sort-a-list-in-python-based-on-another-sorted-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!