Python 检查给定列表是否是较大列表的子列表 def子列表(slist,blist): m=0 子列表是否为False 对于范围(0,len(blist))中的n: 而(n
我上面写的代码是检查给定列表是否是较大列表的“子列表”。因此,如果一个大列表是[3,3,10,4,9],而给定的列表是[3,10,4],那么它是一个子列表,因此它必须返回True。但是我的代码怎么了?当我运行它时,输出是“它不是子列表”,即使它是(函数返回False)。我只想使用循环,没有内置函数。您可以使用:Python 检查给定列表是否是较大列表的子列表 def子列表(slist,blist): m=0 子列表是否为False 对于范围(0,len(blist))中的n: 而(n,python,loops,boolean-logic,Python,Loops,Boolean Logic,我上面写的代码是检查给定列表是否是较大列表的“子列表”。因此,如果一个大列表是[3,3,10,4,9],而给定的列表是[3,10,4],那么它是一个子列表,因此它必须返回True。但是我的代码怎么了?当我运行它时,输出是“它不是子列表”,即使它是(函数返回False)。我只想使用循环,没有内置函数。您可以使用: def sublist(slist, blist): m = 0 is_a_sublist = False for n in range(0, len(blist
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()
对于代码来说,在for循环之后再加上while循环是错误的。在blist上循环只需要for循环 这就是代码出错的原因:
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
输出
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()
解释
代码:
我真的只想使用循环和布尔逻辑,而不是内置函数。@MohamedTlili现在检查我的答案,我希望你最好检查一下所有的l1都在l2中,它们可以是非连续的,而不是sublist@azro忘记提到子列表必须是连续的。例如,[3,9,8]不是[2,3,1,9,7,8]的子列表@MohamedTlili好的,现在肯定更好的答案是使用复杂的函数,只是想依赖循环。你能解释第2行和第3行代码背后的逻辑吗?@MohamedTlili——添加了解释。如果您需要更多信息,请告诉我。
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