繁体   English   中英

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

[英]Comparing two lists in python if elements exist

我有两个列表,我想检查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)

其他可能性,无需创建set

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM