如何检查列表A中的元素是否不存在于Python的列表B中?

时间:2015-06-17 11:34:46

标签: python list

如果我单独使用一个元素,这很容易:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

但是,如果我有两个列表并且必须检查列表A中是否出现列表B中的元素,该怎么办?

A=[1,2,3,4]
B=[4,5,6,7]

如何获得结果显示123不在列表B中?

6 个答案:

答案 0 :(得分:4)

如果列表中的项目是 hashable

>>> 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]

答案 1 :(得分:3)

您还可以使用列表理解:

C=[i for i in A if i not in B]

输出:

[1, 2, 3]

答案 2 :(得分:1)

这是集合上布尔运算的典型案例:

zerotonine = set(range(10))
fourtoten = set(range(4,11))
print "exclusively in one:", zerotonine ^ fourtoten
exclusively in one: set([0, 1, 2, 3, 10])

答案 3 :(得分:1)

set(A).difference(B) # set operation for difference between two collections A and B

答案 4 :(得分:0)

使用列表理解:

truthy回答

any([True for x in [1, 2, 3, 4] if x in [4, 5, 6, 7]])

第二个列表中没有的元素列表

[x for x in [1, 2, 3, 4] if x not in [4, 5, 6, 7]]

答案 5 :(得分:0)

您可以使用>>> a=[1,2,3,4] >>> b=[4,5,6,7] >>> list(set(a)-set(b)) [1, 2, 3] >>>

e.g。

{{1}}