How to subtract two iterables in python

大城市里の小女人 提交于 2020-01-17 04:48:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!