如何在python中减去两个可迭代项 [英] How to subtract two iterables in python

查看:84
本文介绍了如何在python中减去两个可迭代项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个列表A和B.我想获取A中的所有元素,但不获取B中的所有元素.有什么有效的方法吗?

There are two lists A and B. I want to get all the elements in A but not in B. Any efficient way to do this?

推荐答案

您可以使用列表推导为您完成此操作.

You can use a list comprehension to do this for you.

filtered = [i for i in A if i not in B]

如果两个列表都很大,则可能要考虑从B创建一个set,以便更快地查找成员资格

If the lists are both large, you might want to consider creating a set from B for faster membership lookup

setB = set(B)
filtered = [i for i in A if i not in setB]

此解决方案维护A的顺序以及A中存在的所有重复项.

This solution maintains the order of A and any duplicates that exist in A.

这篇关于如何在python中减去两个可迭代项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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