Remove all the elements that occur in one list from another

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

    Python has a language feature called List Comprehensions that is perfectly suited to making this sort of thing extremely easy. The following statement does exactly what you want and stores the result in l3:

    l3 = [x for x in l1 if x not in l2]
    

    l3 will contain [1, 6].

提交回复
热议问题