How to remove every occurrence of sub-list from list

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

    What you are trying to achieve can be done by converting it into list of strings and after replacing again convert it to integer type.

    In a single line you can do it like this

    map(int,list(("".join(map(str, big_list))).replace("".join(map(str, sub_list)),'').replace(''.join((map(str, sub_list))[::-1]),'')))
    

    Input

    big_list = [1, 2, 1, 2, 1]
    sub_list = [1, 2, 1]
    

    Output

    [2, 1]

    Input

    big_list = [2, 1, 2, 3, 1, 2, 4]
    sub_list = [1, 2]
    

    Ouput

    [2, 3, 4]

提交回复
热议问题