简体   繁体   English

在保持顺序的同时设置减法

[英]Set subtraction while retaining order

I know with set subtraction I can do the following: 我知道通过设置减法可以执行以下操作:

l2 = set([4,3,5,2])
l1 = set([3,8])
l2 - l1
set([2, 4, 5])

How would I do this same thing, while keeping the ordering in l1 . 在保持l1顺序的同时,我将如何做同样的事情。 For example: 例如:

l2 = [4,3,5,2] 
l1 [3,8]
# remove 3, keep other ordering
l2 - l1
[4,5,2]
l1 = [4,3,5,2]
l2 = [3]
# remove 3, keep other ordering
st = set(l2)

print([x for x in l1 if x not in st])

[4, 5, 2]

Just make l2 a set and use in keeping elements from l1 that are not in st . 只是让l2一组,并使用in保持从要素l1不在st set lookups are 0(1) so you still have an efficient solution. 集合查找为0(1)因此您仍然有一个有效的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM