如何检查两个列表中的值是否都不存在

时间:2017-01-24 05:26:44

标签: python list

a=[1,2,5]
b=[3,4]
x=8
res= (x not in a) and (x not in b)   #True

但检查它的最好和最快的方法是什么?

3 个答案:

答案 0 :(得分:1)

虽然您的解决方案非常精细且易读,但您可以通过允许可变数量的列表并通过将其包装在函数中来检查给定元素是否包含在其中来使其更通用:

>>> def not_in_any(*lists, key=None):
        for lst in lists:
            if key in lst:
                return False
        return True

>>> not_in_any([2, 5, 7], [8, 9, 23], [34, 56, 78], [32, 91, 6], key=32)
False
>>> not_in_any([2, 5, 7], [8, 9, 23], [34, 56, 78], [31, 91, 6], key=32)
True
>>> 

但是请注意,Python已经提供了一个内置函数 - any(),它已经在我们的函数中提供了for循环的行为:

def not_in_any(key=None, *lists):
    not any(key in l for l in lists)

答案 1 :(得分:0)

a=[1,2,5]
b=[3,4]
x=8
all(x not in i for i in (a, b))

OR:

from itertools import chain
x not in chain(a, b)

答案 2 :(得分:-1)

其他方法是concat并检查: -

a=[1,2,5]
b=[3,4]
x=8
res= x not in a+b  #True