python - 如何检查 List A 中的元素是否不存在于 Python 的 List B 中?

标签 python list

如果我只有一个元素,这很容易:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

But what if I have two lists and have to check if the elements in list A occur in list B?

A=[1,2,3,4]
B=[4,5,6,7]

如何获得显示 123 不在列表 B 中的结果?

最佳答案

如果列表中的项目可散列:

>>> set(A) - set(B)
{1, 2, 3}

否则,您可以使用 filter功能:

>>> list(filter(lambda a: a not in B, A))
[1, 2, 3]

在那种情况下,如果 B排序的,使用 bisect.bisect_left 可能会获得更好的性能以对数方式搜索:

>>> def pred(a):  # if B is already *sorted*
...     from bisect import bisect_left
...     i = bisect_left(B, a)
...     return i == len(B) or B[i] != a
... 
>>> list(filter(pred, A))
[1, 2, 3]

关于python - 如何检查 List A 中的元素是否不存在于 Python 的 List B 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30890402/

相关文章:

python - R的c()在python中的等价函数是什么?

java - Java 中集合的浅拷贝

php - 使用 PHP 和 MySQL 构建任务列表

python - 在字典列表中查找键值

python - 唯一导入 * 只允许在模块级别

python - 如何使PySoundfile在Google Cloud Platform灵活环境上运行?

python - 如何检查变量是 python 列表、numpy 数组还是 pandas 系列

python - 我认为它应该包含每个 "append"的不同列表,但事实并非如此

Python 获取控制台输出

python - 根据python中的数据框重命名fasta文件