下面的代码使用生成器函数从较大的列表中提取子列表。如果你不了解生成器函数背后的机制,它可能不适合做家庭作业,但如果你感兴趣的话,它可能是需要研究的东西。在# A generator function that returns the n-length sublists of list lst
def slider(lst, n):
start = 0
while start + n <= len(lst):
yield lst[start:start+n]
start += 1
# A function that will return True if sequence needle exists in
# haystack, False otherwise
def list_contains(haystack, needle):
for sub in slider(haystack, 3): # Loop through the sublists...
if sub == needle: # ... test for equality ...
return True
return False
# Code
big = [2,4,6,8,0,1,2,3,1,5,7] # Hardcoded here, could be created
# in a loop like you show
seq = [1,2,3] # The sequence you're looking for
print(list_contains(big, seq))
您可以看到生成器函数的输出,如下所示:
^{pr2}$
输出:[2, 4, 6]
[4, 6, 8]
[6, 8, 0]
[8, 0, 1]
[0, 1, 2]
[1, 2, 3]
[2, 3, 1]
[3, 1, 5]
[1, 5, 7]
或者更清楚地说:# [2, 4, 6, 8, 0, 1, 2, 3, 1, 5, 7]
[2, 4, 6]
[4, 6, 8]
[6, 8, 0]
[8, 0, 1]
[0, 1, 2]
[1, 2, 3]
[2, 3, 1]
[3, 1, 5]
[1, 5, 7]