Remove all the elements that occur in one list from another

后端 未结 7 807
旧巷少年郎
旧巷少年郎 2020-11-21 23:45

Let\'s say I have two lists, l1 and l2. I want to perform l1 - l2, which returns all elements of l1 not in l2

7条回答
  •  失恋的感觉
    2020-11-22 00:25

    Expanding on Donut's answer and the other answers here, you can get even better results by using a generator comprehension instead of a list comprehension, and by using a set data structure (since the in operator is O(n) on a list but O(1) on a set).

    So here's a function that would work for you:

    def filter_list(full_list, excludes):
        s = set(excludes)
        return (x for x in full_list if x not in s)
    

    The result will be an iterable that will lazily fetch the filtered list. If you need a real list object (e.g. if you need to do a len() on the result), then you can easily build a list like so:

    filtered_list = list(filter_list(full_list, excludes))
    

提交回复
热议问题