问题描述
我想基于预排序列表在Python中对列表进行排序
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']
谢谢!
推荐答案
In [5]: sorted(unsorted_list, key=presorted_list.index)
Out[5]: ['2C', '2D', '3D', '4D']
或者,为了获得更好的性能(尤其是当len(presorted_list)
大时),
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']
有关如何使用key
进行排序的更多信息,请参见出色的如何进行排序Wiki .
For more on how to sort using key
s, see the excellent Howto Sort wiki.
如果unsorted_list
包含不在presorted_list
中的项目(例如'6D'
),则上述方法将引发错误.您首先必须决定如何对这些项目进行排序.如果要将它们放在列表的末尾,可以使用
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']
这篇关于根据另一个排序列表在python中对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!