How to remove every occurrence of sub-list from list

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

    You can use recursion with a generator:

    def remove(d, sub_list):
       if d[:len(sub_list)] == sub_list and len(sub_list) <= len(d[:len(sub_list)]):
          yield from [[], remove(d[len(sub_list):], sub_list)][bool(d[len(sub_list):])]
       else:
          yield d[0]
          yield from [[], remove(d[1:], sub_list)][bool(d[1:])]
    
    tests = [[[2, 1, 2, 3, 1, 2, 4], [1, 2]], [[1, 2, 1, 2], [1, 2]], [[1, 'a', int, 3, float, 'a', int, 5], ['a', int]], [[1, 1, 1, 1, 1], [1,1,1]]]
    for a, b in tests:
      print(list(remove(a, b)))
    

    Output:

    [2, 3, 4]
    []
    [1, 3, , 5]
    [1, 1]
    

提交回复
热议问题