有两个列表A和B。我想获取A中的所有元素,但不获取B中的所有元素。有什么有效的方法吗?
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
.
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
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
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.