从 Python 中的两个列表中获取差异 [英] Get difference from two lists in Python

查看:50
本文介绍了从 Python 中的两个列表中获取差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表,l1l2.我需要 l1 中不在 l2 中的项目.

I have two lists, l1 and l2. I need items from l1 which are not in l2.

l1 = [2, 3, 4, 5]
l2 = [0, 1, 2, 3]

我只想得到 [4,5] - 只有 l1 中的新值.

I want to get only [4,5] - only new values in l1.

[i for i in l1 if not i in l2 ]

我可以在没有迭代的情况下做到这一点吗?

Can I do that without iteration?

推荐答案

简短的回答,是的:list(set(l1) - set(l2)),尽管这不会保持秩序.

Short answer, yes: list(set(l1) - set(l2)), though this will not keep order.

答案很长,不,因为在内部 CPU 将始终迭代.虽然如果你使用 set() 迭代将被高度优化并且会比你的列表理解快得多(更不用说检查成员资格list中的值是<强>使用集合比列表快得多.

Long answer, no, since internally the CPU will always iterate. Though if you use set() that iteration will be done highly optimized and will be much faster then your list comprehension (not to mention that checking for membership value in list is much faster with sets then lists).

这篇关于从 Python 中的两个列表中获取差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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