How to remove every occurrence of sub-list from list

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

    More readable than any above and with no additional memory footprint:

    def remove_sublist(sublist, mainlist):
    
        cursor = 0
    
        for b in mainlist:
            if cursor == len(sublist):
                cursor = 0
            if b == sublist[cursor]:
                cursor += 1
            else:
                cursor = 0
                yield b
    
        for i in range(0, cursor):
            yield sublist[i]
    

    This is for onliner if you wanted a function from library, let it be this

    [x for x in remove_sublist([1, 2], [2, 1, 2, 3, 1, 2, 4])]
    

提交回复
热议问题