简体   繁体   中英

Comparing two lists in python if elements exist

I have two lists where I want to check if elements from a exists in b

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

This is what I tried ( didn't work though!)

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)

I want to check if elements from a exists in b and should set a flag accordingly. Any thoughts?

Your code returns as soon as first element exists in both lists. To check all elements you could try this for example:

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

Other possibility, without creating a set :

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

And in case you were curious what exactly in your code is wrong, this is the fix in its current form (but it's not very 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

And finally, your function name isn't very readable. detect is too ambiguous. Consider other more verbose names, like isSubset etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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