从另一个列表中删除一个列表中出现的所有元素

本文翻译自:Remove all the elements that occur in one list from another

Let's say I have two lists, l1 and l2 . 假设我有两个列表l1l2 I want to perform l1 - l2 , which returns all elements of l1 not in l2 . 我要执行l1 - l2 ,它返回l1中所有不在l2元素。

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? 什么是Python高效的方法?

As an example, if I have l1 = [1,2,6,8] and l2 = [2,3,5,8] , l1 - l2 should return [1,6] 例如,如果我有l1 = [1,2,6,8] and l2 = [2,3,5,8] ,则l1 - l2应该返回[1,6]


#1楼

参考:https://stackoom.com/question/HfWj/从另一个列表中删除一个列表中出现的所有元素


#2楼

替代解决方案:

reduce(lambda x,y : filter(lambda z: z!=y,x) ,[2,3,5,8],[1,2,6,8])

#3楼

Python has a language feature called List Comprehensions that is perfectly suited to making this sort of thing extremely easy. Python具有称为List Comprehensions的语言功能,非常适合使此类事情变得非常容易。 The following statement does exactly what you want and stores the result in l3 : 下面的语句完全满足您的要求,并将结果存储在l3

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

l3 will contain [1, 6] . l3将包含[1, 6]


#4楼

One way is to use sets: 一种方法是使用集合:

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

#5楼

Use the Python set type. 使用Python设置类型。 That would be the most Pythonic. 那将是最Python的。 :) :)

Also, since it's native, it should be the most optimized method too. 另外,由于它是本机的,因此它也应该是最优化的方法。

See: 看到:

http://docs.python.org/library/stdtypes.html#set http://docs.python.org/library/stdtypes.html#set

http://docs.python.org/library/sets.htm (for older python) http://docs.python.org/library/sets.htm (适用于较旧的python)

# Using Python 2.7 set literal format.
# Otherwise, use: l1 = set([1,2,6,8])
#
l1 = {1,2,6,8}
l2 = {2,3,5,8}
l3 = l1 - l2

#6楼

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). 在此处扩展Donut的答案和其他答案,通过使用生成器理解而不是列表理解,以及使用set数据结构(由于in运算符在列表上为O(n)但在O( 1)在集合上)。

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 (eg if you need to do a len() on the result), then you can easily build a list like so: 如果您需要一个真正的列表对象(例如,如果需要对结果执行len() ),则可以轻松构建一个列表,如下所示:

filtered_list = list(filter_list(full_list, excludes))
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值