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
. 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
. set lookups are 0(1)
so you still have an efficient solution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.