如果元素存在,则在python中比较两个列表

我有两个列表,我想检查b中的元素是否存在

a=[1,2,3,4]
b=[4,5,6,7,8,1]

这就是我尝试过的(尽管不起作用!)

a=[1,2,3,4]
b=[4,5,6,7,3,1]

def detect(list_a, list_b):
    for item in list_a:
        if item in list_b:
            return True
    return False  # not found

detect(a,b)

我想检查b中是否存在元素,并应相应地设置一个标志.有什么想法吗?

最佳答案 只要第一个元素存在于两个列表中,您的代码就会返回.要检查所有元素,您可以尝试这样做:

def detect(list_a, list_b):
    return set(list_a).issubset(list_b)

其他可能性,无需创建集合:

def detect(list_a, list_b):
    return all(x in list_b for x in list_a)

如果你很好奇你的代码究竟是什么错,那就是当前形式的修复(但它不是非常pythonic):

def detect(list_a, list_b):
    for item in list_a:
        if item not in list_b:
            return False       # at least one doesn't exist in list_b

    return True   # no element found that doesn't exist in list_b
                  # therefore all exist in list_b

最后,您的函数名称不是很易读.检测太模糊了.考虑其他更冗长的名称,如isSubset等.

点赞