问题描述
假设我有两个列表,l1
和l2
.我要执行l1 - l2
,它返回l1
中所有不在l2
中的元素.
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
.
我可以想到一个幼稚的循环方法来执行此操作,但这实际上效率很低. pythonic的有效方法是什么?
I can think of a naive loop approach to doing this, but that is going to be really inefficient. What is a pythonic and efficient way of doing this?
例如,如果我有l1 = [1,2,6,8] and l2 = [2,3,5,8]
,则l1 - l2
应该返回[1,6]
As an example, if I have l1 = [1,2,6,8] and l2 = [2,3,5,8]
, l1 - l2
should return [1,6]
推荐答案
Python具有一种称为列表理解非常适合使此类事情变得非常容易.以下语句完全满足您的要求,并将结果存储在l3
中:
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
将包含[1, 6]
.
这篇关于从另一个列表中删除一个列表中出现的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!