在Python中比较两个列表是否存在相同元素

3

我有两个列表,想要检查a中的元素是否存在于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)

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

1
问题在于,一旦找到ab中第一个相同的元素,您就会立即返回True - tobias_k
1
你需要一个标志列表来逐个检查a的元素是否存在于b中,还是只需要一个布尔值来判断a的所有元素是否都存在于b中? - leeladam
只有当a中的所有元素都存在于b中时,才应该提高标志。 - user741592
1
使用正确的数据结构,参考 http://docs.python.org/2/library/sets.html。 - shevski
1个回答

7

当两个列表中都存在第一个元素时,您的代码就会返回。为了检查所有元素,您可以尝试以下代码:

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)

如果你好奇的话,可以看看你代码里到底哪里出了问题,这是当前形式下的修复方法(但它不太符合Python的风格):

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 等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接