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

2024-09-29 02:22:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始使用Python。我知道这可能是个愚蠢的问题,因为我觉得这是一个非常基本的问题。在

我需要将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

在上面的例子中,我想看看children1列表值是否在children2列表中,然后返回true。在


Tags: true列表returnifherechecklistfirst
2条回答

您可以使用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)

退货

^{pr2}$

sets有一个^{}方法,可以方便地重载为<=

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

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

相关问题 更多 >