简体   繁体   English

如何有效地比较Python中的两个列表?

[英]How to compare two lists in Python efficiently?

I have recently started working with Python. 我最近开始使用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. 我需要比较first listsecond list ,如果first list值有在second list ,然后我想返回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. 在我上面的例子中,我想看看children1列表值有在children2列表中,则返回true。

set s have an issubset method, which is conveniently overloaded to <= : set具有一个issubset方法,可以方便地重载为<=

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 你可以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

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

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