Remove all the elements that occur in one list from another

后端 未结 7 670
旧巷少年郎
旧巷少年郎 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:18

    One way is to use sets:

    >>> set([1,2,6,8]) - set([2,3,5,8])
    set([1, 6])
    

    Note, however, that sets do not preserve the order of elements, and cause any duplicated elements to be removed. The elements also need to be hashable. If these restrictions are tolerable, this may often be the simplest and highest performance option.

提交回复
热议问题