How to remove every occurrence of sub-list from list

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

    A recursive approach:

    def remove(lst, sub):
        if not lst:
            return []
        if lst[:len(sub)] == sub:
            return remove(lst[len(sub):], sub)
        return lst[:1] + remove(lst[1:], sub)
    print(remove(big_list, sub_list))
    

    This outputs:

    [2, 3, 4]
    

提交回复
热议问题