【问题标题】:Check if a given list is a sublist of a larger list [duplicate]检查给定列表是否是更大列表的子列表[重复]
【发布时间】:2020-03-25 21:33:46
【问题描述】:
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】:

您的代码有一个 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

【讨论】:

  • 你能解释一下第 2 行和第 3 行代码背后的逻辑吗?
  • @MohamedTlili--添加了解释。如果您需要更多信息,请告诉我。
【解决方案2】:

你可以使用:

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

【讨论】:

  • 我真的只想使用循环和布尔逻辑,而不是内置函数。
  • @MohamedTlili 现在检查我的答案,我希望会更好
  • 你只检查所有 l1 都在 l2 中,它们可以是不连续的,它不会是一个子列表
  • @azro 忘记提及子列表必须是连续的。例如 [3,9,8] 不是 [2,3,1,9,7,8] 的子列表
  • @MohamedTlili 好的,现在肯定更好
猜你喜欢
  • 2017-06-08
  • 2020-05-14
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
  • 2021-02-15
  • 2019-03-19
相关资源
最近更新 更多