How to remove every occurrence of sub-list from list

前端 未结 13 562
走了就别回头了
走了就别回头了 2021-01-07 16:16

I have two lists:

big_list = [2, 1, 2, 3, 1, 2, 4]
sub_list = [1, 2]

I want to remove all sub_list occurrences in big_list.

result

13条回答
  •  有刺的猬
    2021-01-07 16:39

    Try del and slicing. The worst time complexity is O(N^2).

    sub_list=['a', int]
    big_list=[1, 'a', int, 3, float, 'a', int, 5]
    i=0
    while i < len(big_list):
        if big_list[i:i+len(sub_list)]==sub_list:
            del big_list[i:i+len(sub_list)]
        else:
            i+=1
    
    print(big_list)
    

    result:

    [1, 3, , 5]
    

提交回复
热议问题