检查给定列表是否是更大列表的子列表

Check if a given list is a sublist of a larger list

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()

我上面写的代码是检查给定的列表是否是更大列表的"sublist"。所以,如果一个大列表是 [3,3,10,4,9],而给定的列表是 [3,10,4],那么它是一个子列表,所以它必须 return 为真。但是我的代码有什么问题?当我 运行 它时,输出是 "It ain't a sublist" 即使它是(函数 returns False)。我只想使用循环,没有内置函数。

您可以使用:

def sublist(l2, l1):
    for i in range(0, len(l2) - len(l1) + 1):
        if l2[i] == l1[0]:
            for j in range(1, len(l1)):
                if l2[i + j] != l1[j]:
                    break
            else:
                return True
    return False


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

sublist(l1, l2)
# True

您的代码中有一个 for 循环后跟一个 while 循环是错误的。只需要 for 循环来遍历 blist。

所以这是错误的代码:

for n in range(0, len(blist)):
     while (n < len(blist) and m < len(blist)) and is_a_sublist == False:

简化代码

通过简化循环,删除多余的变量和步骤,您的代码可以简化为以下内容:

def sublist(slist, blist):
  for n in range(len(blist)-len(slist)+1):
    if slist == blist[n:n+len(slist)]:
      return True
  return False

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

    if sublist(test_list,original_list):
        print("It is a sublist!")
    else:
        print("It ain't a sublist!")

main()

输出

It is a sublist!

说明

代码:

for n in range(len(blist)-len(slist)+1):
# We're looking for a starting index between
# 0 and len(blist)-len(slist)
# The reason it can be at most 
# len(blist)-len(list) 
# is that's the max index that still could 
# have len(slist) elements
# range(len(blist)-len(slist)+1) provides
# numbers from 0 to en(blist)-len(slist)
   if slist == blist[n:n+len(slist)]:
 # Check if we have a match from n to
 # n + len(slist) - 1 (i.e. since slice
 # a:b means index of elements from a to b-1