How to remove every occurrence of sub-list from list

前端 未结 13 611
走了就别回头了
走了就别回头了 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条回答
  •  -上瘾入骨i
    2021-01-07 16:31

    Kinda different approach in Python 2.x!

    from more_itertools import locate, windowed
    big_list = [1, 2, 1, 2, 1]
    sub_list = [1, 2, 1]
    
    """
    Fetching all starting point of indexes (of sub_list in big_list)
    to be removed from big_list. 
    """
    
    i = list(locate(windowed(big_list, len(sub_list)), pred=lambda x: x==tuple(sub_list)))
    
    """ 
    Here i comes out to be [0, 2] in above case. But index from 2 which 
    includes 1, 2, 1 has last 1 from the 1st half of 1, 2, 1 so further code is
    to handle this case.
    PS: this won't come for-
    big_list = [2, 1, 2, 3, 1, 2, 4]
    sub_list = [1, 2]
    as here i comes out to be [1, 4]
    """
    
    # The further code.
    to_pop = []
    for ele in i:
        if to_pop:
            if ele == to_pop[-1]:
                continue
        to_pop.extend(range(ele, ele+len(sub_list)))
    
    # Voila! to_pop consists of all the indexes to be removed from big_list.
    
    # Wiping out the elements!
    for index in sorted(to_pop, reverse=True):
        del big_list[index]
    

    Note that you need to delete them in reverse order so that you don't throw off the subsequent indexes.

    In Python3, signature of locate() will differ.

提交回复
热议问题