python列表排序sort是什么实现的_根据另一个排序列表在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']

Thanks!

解决方案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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值