如果我单独使用一个元素,这很容易:
>>> 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
中?
答案 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}}