Sort a list in python based on another sorted list

后端 未结 1 1664
独厮守ぢ
独厮守ぢ 2021-01-05 13:56

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\',         


        
相关标签:
1条回答
  • 2021-01-05 14:35
    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']
    
    0 讨论(0)
提交回复
热议问题