How to remove every occurrence of sub-list from list

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

    A improved version to check whether lst[i:i+len(sub)] < len(lst)

    def remove_sublist(lst, sub):
        i = 0
        out = []
        sub_len = len(sub)
        lst_len = len(lst)
        while i < lst_len:
            if (i+sub_len) < lst_len:
                if lst[i: i+sub_len] == sub:
                    i += sub_len
                else:
                    out.append(lst[i])
                    i += 1
            else:
                out.append(lst[i])
                i += 1
    
        return out
    

提交回复
热议问题