问题
There are two lists A and B. I want to get all the elements in A but not in B. Any efficient way to do this?
回答1:
You can use a list comprehension to do this for you.
filtered = [i for i in A if i not in B]
If the lists are both large, you might want to consider creating a set
from B
for faster membership lookup
setB = set(B)
filtered = [i for i in A if i not in setB]
This solution maintains the order of A
and any duplicates that exist in A
.
回答2:
i always like to use sets for this:
set(A) - set(B)
edit: except if A has duplicates or you care about order, then use @Cyber's answer
回答3:
sets are great for this purpose
set(A) - set(B)
eg
>>> set([2,2,2,3,3,4])- set([1,2,2,4,5])
set([3])
btw. this looks like this
来源:https://stackoverflow.com/questions/28570985/how-to-subtract-two-iterables-in-python