Delete all occurrences of specific values from list of lists python

后端 未结 2 557
猫巷女王i
猫巷女王i 2021-01-27 16:40

As far as I can see this question (surprisingly?) has not been asked before - unless I am failing to spot an equivalent question due to lack of experience. (Similar questions h

相关标签:
2条回答
  • 2021-01-27 16:46

    I'd write a function that just takes one list (or iterable) and a set, and returns a new list with the values from the set removed:

    def list_without_values(L, values):
        return [l for l in L if l not in values]
    

    Then I'd turn list_A into a set for fast checking, and loop over the original list:

    set_A = set(list_A)
    list_of_lists = [list_without_values(L, set_A) for L in list_of_lists]
    

    Should be fast enough and readibility is what matters most.

    0 讨论(0)
  • 2021-01-27 16:59

    Using list comprehension should work as:

    new_list = [[i for i in l if i not in list_A] for l in list_of_list]
    

    After that, if you want to remove empty lists, you can make:

    for i in new_list:
        if not i:
            new_list.remove(i)
    

    of, as @ferhatelmas pointed in comments:

    new_list = [i for i in new_list if i]
    

    To avoid duplicates in list_A you can convert it to a set before with list_A = set(list_A)

    0 讨论(0)
提交回复
热议问题