首页 > 解决方案 > 列表 A 是否有任何不在列表 B 中的项目

问题描述

我试图弄清楚如果我的列表包含不在我的黑名单中的任何项目,我如何返回 true。听起来可能很奇怪,但如果列表完全由我的黑名单中的项目组成,我只想返回 false。

这就是我的意思...

blacklist = [one, two, three]

这是我希望发生在以下情况...

one two three four = true because four is not in the blacklist
one = false because one is in the blacklist
one two three = false because all are in the blacklist
five = true because five is not in the blacklist

希望这是有道理的。

标签: pythonlist

解决方案


您可以通过减去它们来找到 2 个列表之间的差异set()

allowed = list(set(yourlist)-set(blacklist))

这将返回一个列表以查看您的列表和黑名单之间的区别,因此,您可以使用条件来查看列表是否为空,以返回 false 或 true。


推荐阅读