简体   繁体   中英

How to compare two lists in Python efficiently?

I have recently started working with Python. I know it might be a silly question as it sounds very basic question to me.

I need to compare first list with second list and if first list values are there in the second list , then I want to return true.

children1 = ['test1']
children2 = ['test2', 'test5', 'test1']

if check_list(children1):
    print "hello world"


def check_list(children):
    # some code here and return true if it gets matched.
    # compare children here with children2, if children value is there in children2
    # then return true otherwise false

In my above example, I want to see if children1 list value is there in children2 list, then return true.

set s have an issubset method, which is conveniently overloaded to <= :

def check_list(A, B):
    return set(A) <= set(B)

check_list(children1, children2) # True
check_list([1,4], [1,2,3]) # False

You can use all

def check_list(child1, child2):
    child2 = set(child2)
    return all(child in child2 for child in child1)

children1 = ['test1']
children2 = ['test2', 'test5', 'test1']
print check_list(children1, children2)

Returns

True

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