如果列表项不在列表中那么

Den*_*ang 0 python if-statement list

所以我想知道是否有更"美丽"的方式来做到这一点.目前我有超过一千个列表list_of_lists,其中每个列表看起来像这样:

list_of_items = ["dog", "mouse", "cow", "goat", "fish"]
Run Code Online (Sandbox Code Playgroud)

有些列表包含其他动物/字符串,并且没有上述部分内容.这取决于.

我现在想做一个if语句说:

list_of_items = ["dog", "mouse", "cow", "goat", "fish"]
for x in list_of_items:
    if "cow" not in list_of_items and "cat" not in list_of_items:
       print("Cat or Cow could not be found in list {}".format(x))
Run Code Online (Sandbox Code Playgroud)

这完全符合它的预期.如果它在当前列表中找到"cat"或"cow",则不会打印任何内容.但如果两者都找不到,则会发生打印声明.

我的问题是我有几个"牛","猫",所以我需要包含在我的if语句中.如果我有10个,作为一个例子,它会变得有点长而丑陋.那么有什么方法可以说:if list_of_animals not in list_of_items:,哪里list_of_animals只是一个应该包含在and声明中的字符串列表?

Rak*_*esh 7

您可以将列表转换为set和使用issubset

例如:

list_of_items = set(["dog", "mouse", "cow", "goat", "fish", "cat"])
toCheck = set(["cow", "cat"])

if toCheck.issubset(list_of_items):
    print("Ok")
Run Code Online (Sandbox Code Playgroud)

根据评论进行编辑

if any(i in list_of_items for i in toCheck):
    print("Ok")
Run Code Online (Sandbox Code Playgroud)