如何对另一个列表进行排序? [英] How to sort one list based on another?

查看:99
本文介绍了如何对另一个列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表,一个参考和一个输入列表

I have two list, one reference and one input list

Ref = [3, 2, 1, 12, 11, 10, 9, 8, 7, 6, 5, 4]
Input = [9, 5, 2, 3, 10, 4, 11, 8]

我想按参考"的顺序对输入"列表进行排序.如果输入"列表中缺少某些元素,则可以跳过并查找其他元素.

I want to sort Input list, in the order as that of Ref. If some element is missing in Input list, it can skip and go for the other element.

因此基于引用"列表排序的输入"列表将是这样

Hence sorted Input list, based on Ref list will be like this

Sorted_Input = [3, 2, 11, 10, 9, 8, 5, 4]

推荐答案

我认为这可以回答您的问题:

I think this answers your question:

>>> [x for x in Ref if x in Input]
>>> [3, 2, 11, 10, 9, 8, 5, 4]

希望有帮助.

更新: 将Input设置为set以获得更快的访问速度:

UPDATE: Making Input a set for faster access:

>>> Input_Set = set(Input)
>>> [x for x in Ref if x in Input_Set]
[3, 2, 11, 10, 9, 8, 5, 4]

这篇关于如何对另一个列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆