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

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

问题描述

假设我有两个列表,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] 和 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 有一个名为 List Comprehensions 非常适合让这种事情变得非常简单.以下语句完全符合您的要求并将结果存储在 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天全站免登陆