📜  Python – 检查列表中的子列表

📅  最后修改于: 2022-05-13 01:54:31.785000             🧑  作者: Mango

Python – 检查列表中的子列表

有时,在使用Python列表时,我们可能会遇到需要检查特定子列表是否包含在列表中的确切序列中的问题。此任务可以在许多领域应用,例如学校编程和 Web 开发。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环+列表切片
上述功能的组合可以用来解决这个问题。在此,我们使用列表切片技术通过增量切片来执行检查子列表的任务。

Python3
# Python3 code to demonstrate working of
# Check for Sublist in List
# Using loop + list slicing
 
# initializing list
test_list = [5, 6, 3, 8, 2, 1, 7, 1]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing sublist
sublist = [8, 2, 1]
 
# Check for Sublist in List
# Using loop + list slicing
res = False
for idx in range(len(test_list) - len(sublist) + 1):
        if test_list[idx : idx + len(sublist)] == sublist:
            res = True
            break
         
# printing result
print("Is sublist present in list ? : " + str(res))


Python3
# Python3 code to demonstrate working of
# Check for Sublist in List
# Using any() + list slicing + generator expression
 
# initializing list
test_list = [5, 6, 3, 8, 2, 1, 7, 1]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing sublist
sublist = [8, 2, 1]
 
# Check for Sublist in List
# Using any() + list slicing + generator expression
res = any(test_list[idx : idx + len(sublist)] == sublist
        for idx in range(len(test_list) - len(sublist) + 1))
         
# printing result
print("Is sublist present in list ? : " + str(res))


输出 :
The original list : [5, 6, 3, 8, 2, 1, 7, 1]
Is sublist present in list ? : True


方法 #2:使用 any() + 列表切片 + 生成器表达式
上述功能的组合就是用来解决这个问题的。在此,我们使用 any() 执行检查任何等于所需长度的子列表的任务,并且列表切片用于切片所需长度的增量列表。

Python3

# Python3 code to demonstrate working of
# Check for Sublist in List
# Using any() + list slicing + generator expression
 
# initializing list
test_list = [5, 6, 3, 8, 2, 1, 7, 1]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing sublist
sublist = [8, 2, 1]
 
# Check for Sublist in List
# Using any() + list slicing + generator expression
res = any(test_list[idx : idx + len(sublist)] == sublist
        for idx in range(len(test_list) - len(sublist) + 1))
         
# printing result
print("Is sublist present in list ? : " + str(res))
输出 :
The original list : [5, 6, 3, 8, 2, 1, 7, 1]
Is sublist present in list ? : True