按其他列表中项目的存在对列表进行排序 [英] Sort a list by presence of items in another list

查看:69
本文介绍了按其他列表中项目的存在对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个列表:

a = ['30', '10', '90', '1111', '17']
b = ['60', '1201', '30', '17', '900']

您如何最有效地对此进行排序,例如:

How would you sort this most efficiently, such that:

列表b相对于a进行了排序. b中的唯一元素应放在排序列表的末尾. a中的唯一元素可以忽略.

list b is sorted with respect to a. Unique elements in b should be placed at the end of the sorted list. Unique elements in a can be ignored.

示例输出:

c = ['30', '17', '60', '1201', '900']

对不起,这是一个简单的问题.我的尝试停留在采取交叉路口的位置.

Sorry, it's a simple question. My attempt is stuck at the point of taking the intersection.

intersection = sorted(set(a) & set(b), key = a.index)

推荐答案

这里没有必要进行实际排序.您希望a中的元素位于b中,并且顺序与a中的元素相同;其次是b中不在a中的元素,其顺序与在b中的顺序相同.

There is no need to actually sort here. You want the elements in a which are in b, in the same order as they were in a; followed by the elements in b which are not in a, in the same order as they were in b.

我们可以使用两个过滤器,使用用于快速成员资格测试的集合来做到这一点:

We can just do this with two filters, using the sets for fast membership tests:

>>> a = ['30', '10', '90', '1111', '17']
>>> b = ['60', '1201', '30', '17', '900']
>>> a_set = set(a)
>>> b_set = set(b)
>>> [*filter(lambda x: x in b_set, a), *filter(lambda x: x not in a_set, b)]
['30', '17', '60', '1201', '900']

或者,如果您更喜欢理解:

Or if you prefer comprehensions:

>>> [*(x for x in a if x in b_set), *(x for x in b if x not in a_set)]
['30', '17', '60', '1201', '900']

两者都需要线性时间,这比排序要好.

Both take linear time, which is better than sorting.

这篇关于按其他列表中项目的存在对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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