如何检查列表 1 中的任何元素是否不存在于列表 2 中? - python

How to check if any element in list 1 is not present in list 2? - python

我有 2 个列表:

list1 = [1,2,3,4]
list2 = [1,2,3]

如何检查 list1 中是否有任何不在 list2 中的元素?

我当前的代码由于某种原因不起作用:

if not any(item in list1 for item in list2):
    print(True)

我也试过相反的方法,但还是不行:

if not any(item in list2 for item in list1):
    print(True)

所以理想情况下我应该得到 True 作为输出,因为 list1 中的元素 4 在 list2 中不存在,但我不存在。

我也想知道我的代码不正确的原因。提前致谢。

您正在接受整张支票的底片。这将 return 正确的结果

list1 = [1,2,3,4]
list2 = [1,2,3]
if any(item not in list2 for item in list1):
    print(True)

问题在于

any(item in list2 for item in list1)

return True 如果 list2 中的任何项目在 list1 中,我们可以同意存在。另一种选择是使用

all(item in list2 for item in list1)

这将 return False 因为并非 list1 中的所有 items 都在 list2 中。如果您用 not all 否定它,您将获得预期的结果。