如果我只有一个元素,这很容易:
>>> 3 not in [2, 3, 4] False >>> 3 not in [4, 5, 6] True
But what if I have two lists and have to check if the elements in list A
occur in list B
?
A=[1,2,3,4]
B=[4,5,6,7]
如何获得显示 1
、2
、3
不在列表 B
中的结果?
最佳答案
如果列表中的项目可散列:
>>> set(A) - set(B)
{1, 2, 3}
否则,您可以使用 filter
功能:
>>> list(filter(lambda a: a not in B, A))
[1, 2, 3]
在那种情况下,如果 B
是排序的,使用 bisect.bisect_left
可能会获得更好的性能以对数方式搜索:
>>> def pred(a): # if B is already *sorted*
... from bisect import bisect_left
... i = bisect_left(B, a)
... return i == len(B) or B[i] != a
...
>>> list(filter(pred, A))
[1, 2, 3]
关于python - 如何检查 List A 中的元素是否不存在于 Python 的 List B 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30890402/