如果短列表中的元素都在长列表中,而不使用Python更改序列,那么如何从长列表中查找短列表?

如果短列表中的元素都在长列表中,而不使用Python更改序列,那么如何从长列表中查找短列表?,python,list,nested,duplicates,Python,List,Nested,Duplicates,我有一个嵌套列表: a=[[1,2,3],[0,1,2,3,4],[5,7,9],[5,6,7,8,9],[7,10],[10,7,2,1]] 现在,我想删除[1,2,3],因为它包含在[0,1,2,3,4]中。我需要保留[5,7,9],因为虽然它包含在[5,6,7,8,9]中,但中间有一些数字。此外,还应保留[7,10],因为这些数字在[10,7,2,1]中的顺序错误。因此,简化列表为: a=[[0,1,2,3,4],[5,7,9],[5,6,7,8,9],[7,10],[10,7,2,1]

我有一个嵌套列表:

a=[[1,2,3],[0,1,2,3,4],[5,7,9],[5,6,7,8,9],[7,10],[10,7,2,1]]
现在,我想删除[1,2,3],因为它包含在[0,1,2,3,4]中。我需要保留[5,7,9],因为虽然它包含在[5,6,7,8,9]中,但中间有一些数字。此外,还应保留[7,10],因为这些数字在[10,7,2,1]中的顺序错误。因此,简化列表为:

a=[[0,1,2,3,4],[5,7,9],[5,6,7,8,9],[7,10],[10,7,2,1]]

因此,我需要删除短子列表,如果它们包含在长子列表中,而没有任何更改。有人能帮我离开这里吗?

您可以两次向后循环
a
的索引,从最后一个子列表的第二个开始,检查该列表是否包含在下一个子列表中

要测试它是否包含在内,您必须测试第二个列表中所有可能的起始位置,然后检查每对项目是否相同

a = [[1,2,3], [0,1,2,3,4], [5,7,9], [5,6,7,8,9], [7,10], [10,7,2,1]]

def included_in(list1, list2):
    "test if list1 is included in list2"
    r = range(len(list1))
    for start_pos in range(len(list2) - len(list1)):
        for offset in r:
            if list2[start_pos + offset] != list1[offset]:
                break
        else:
            # we got through all the positions in list1 without finding 
            # corresponding element of list2 that *didn't* match
            return True
    # we got through all the starting positions in list2 without finding 
    # a complete match
    return False
            

for index in range(len(a)-2, -1, -2):
    list1 = a[index]
    list2 = a[index + 1]
    if included_in(list1, list2):
        a.pop(index)

print(a)
这将提供以下输出:

[[0, 1, 2, 3, 4], [5, 7, 9], [5, 6, 7, 8, 9], [7, 10], [10, 7, 2, 1]]

@我希望你能明白为什么主回路是反向的。您需要能够删除一个元素(在本例中是一个子列表),而不会中断仍需处理的元素的索引。谢谢!我正在通读代码。当做