如果我只有一个元素,这很容易:
>>> 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]
我该如何获得一个结果,显示1
、2
、3
不在列表B
中?
如果列表中的项是可哈希的:
>>> set(A) - set(B)
{1, 2, 3}
filter
函数: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]
C=[i for i in A if i not in B]
输出:
[1, 2, 3]
使用列表推导:
真值答案
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]]
set(A).difference(B) # set operation for difference between two collections A and B
zerotonine = set(range(10))
fourtoten = set(range(4,11))
print "exclusively in one:", zerotonine ^ fourtoten
exclusively in one: set([0, 1, 2, 3, 10])
set(A).symmetric_difference(B)
相同,其结果与set(B).symmetric_difference(A)
相同。请注意,set(A).difference(B)
可能会返回与set(B).difference(A)
不同的结果(“在A中但不在B中”与“在B中但不在A中”),如果您正在寻找这样的属性(正如问题的标题所暗示的那样)。 - Daniel F你可以使用 set
。
例如:
>>> a=[1,2,3,4]
>>> b=[4,5,6,7]
>>> list(set(a)-set(b))
[1, 2, 3]
>>>