array filter in python?

后端 未结 10 1112
一向
一向 2020-12-14 05:27

For example, I have two lists

 A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A


the result should be [7, 8, 10, 11]; t         


        
10条回答
  •  一整个雨季
    2020-12-14 05:59

    This was just asked a couple of days ago (but I cannot find it):

    >>> A = [6, 7, 8, 9, 10, 11, 12]
    >>> subset_of_A = set([6, 9, 12])
    >>> [i for i in A if i not in subset_of_A]
    [7, 8, 10, 11]
    

    It might be better to use sets from the beginning, depending on the context. Then you can use set operations like other answers show.

    However, converting lists to sets and back only for these operations is slower than list comprehension.

提交回复
热议问题