我知道通过集合减法我可以执行以下操作:
l2 = set([4,3,5,2])
l1 = set([3,8])
l2 - l1
set([2, 4, 5])
我如何做同样的事情,同时保持 l1
中的顺序。例如:
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]
只需将 l2
设为一个集合,并使用 in
保留 l1
中不在 st
中的元素即可。设置查找为0(1)
,因此您仍然拥有有效的解决方案。
关于python - 设置减法同时保留顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28651329/