检查给定列表是否为较大列表的子列表

问题描述 投票:0回答:1
def sublist(slist, blist):
    m = 0
    is_a_sublist = False
    for n in range(0, len(blist)):
     while (n < len(blist) and m < len(blist)) and is_a_sublist == False:
            spliced_list = blist[n:m]
            if spliced_list == slist:
                is_a_sublist = True
            else:
                m += 1

    return is_a_sublist

def main():
    test_list = ["a",9,1,3.14,2]
    original_list = ["a",1,"a",9,1,3.14,2]

    is_a_sublist = sublist(test_list,original_list)

    if is_a_sublist == True:
        print("It is a sublist!")
    else:
        print("It ain't a sublist!")


main()

我在上面编写的代码是检查给定列表是否为较大列表的“子列表”。因此,如果大列表为[3,3,10,4,9],而给定列表为[3,10,4],则它是一个子列表,因此必须返回True。但是我的代码怎么了?当我运行它时,即使输出是“它不是子列表”(函数返回False)。我只想使用循环,没有内置函数。

python loops boolean-logic
1个回答
0
投票
l1 = [3,10,4] l2 = [3,3,10,4,9] all(e in l2 for e in l1)

或:

l1 = [3,10,4]
l2 = [3,3,10,4,9]

set(l1).issubset(l2)

或者如果您想使用for循环:

def sublist(l1, l2):
    for l in l1:
        if l not in l2:
            return False

    return True
© www.soinside.com 2019 - 2024. All rights reserved.