【问题标题】:How to find the short list from a long list if the elements in the short one are all in the long one without changing the sequence using Python? [closed]如果短列表中的元素都在长列表中而不使用Python更改序列,如何从长列表中找到短列表? [关闭]
【发布时间】:2020-08-08 09:29:14
【问题描述】:

我有一个嵌套列表:

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]]

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

【问题讨论】:

    标签: python list nested duplicates


    【解决方案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]]
    

    【讨论】:

    • @FengChen 我希望你明白为什么主循环是向后。您需要能够删除一个元素(在这种情况下是一个子列表),而不会破坏您仍要处理的元素的索引。
    • 谢谢!我正在阅读代码。问候。
    猜你喜欢
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-17
    相关资源
    最近更新 更多