How to remove every occurrence of sub-list from list

前端 未结 13 791
走了就别回头了
走了就别回头了 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:51

    Use itertools.zip_longest to create n element tuples (where n is length of sub_list) and then filter the current element and next n-1 elements when one of the element matched the sub_list

    >>> from itertools import zip_longest, islice
    >>> itr = zip_longest(*(big_list[i:] for i in range(len(sub_list))))
    >>> [sl[0] for sl in itr if not (sl == tuple(sub_list) and next(islice(itr, len(sub_list)-2, len(sub_list)-1)))]
    [2, 3, 4]
    

    To improve the efficiency, you can calculate tuple(sub_list) and len(sub_list) before hand you start filtering

    >>> l = len(sub_list)-1
    >>> tup = tuple(sub_list)
    >>> [sl[0] for sl in itr if not (sl == tup and next(islice(itr, l-1, l)))]
    [2, 3, 4]
    

提交回复
热议问题