从另一个列表中删除一个列表中出现的所有元素 [英] Remove all the elements that occur in one list from another

查看:35
本文介绍了从另一个列表中删除一个列表中出现的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个列表,l1l2.我要执行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].

这篇关于从另一个列表中删除一个列表中出现的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆