如果列表项不在列表中,则

时间:2018-07-10 10:50:41

标签: python list if-statement

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

list_of_items = ["dog", "mouse", "cow", "goat", "fish"]

其中一些列表包含其他动物/字符串,但其中一些没有。这取决于。

我现在想做一个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))

这完全符合预期。如果在当前列表中找到“ cat”或“ cow”,则不会打印任何内容。但是,如果没有找到,就会出现打印语句。

我的问题是我有几个“牛”,“猫”,因此需要在if语句中包括它们。以我为例,如果有10个,那么看起来会很长很丑。因此,有什么方法可以说:if list_of_animals not in list_of_items:,其中list_of_animals只是应该包含在and语句中的字符串的列表?

4 个答案:

答案 0 :(得分: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")

根据评论进行编辑

if any(i in list_of_items for i in toCheck):
    print("Ok")

答案 1 :(得分:1)

如果您希望其中任何一个匹配,也许是这样的事情?

a = ["dog", "mouse", "goat", "fish"]
b = ["cat", "cow"]
if(any(x in a for x in b)):
    print("True")
else:
    print("False")

返回错误

a = ["dog", "mouse", "cow", "goat", "fish"]
b = ["cat", "cow"]
if(any(x in a for x in b)):
    print("True")
else:
    print("False")

返回True

如果您希望两者都匹配,则:

a = ["dog", "mouse", "cow", "goat", "fish"]
b = ["cat", "cow"]
if(all(x in a for x in b)):
    print("True")
else:
    print("False")

返回错误

a = ["dog", "mouse", "cow", "cat", "goat", "fish"]
b = ["cat", "cow"]
if(all(x in a for x in b)):
    print("True")
else:
    print("False")

返回True

答案 2 :(得分:1)

尝试一下:

list_of_items = ["dog", "mouse", "cow", "goat", "fish"]
another_list = ["cow", "cat"]
for x in list_of_items:
    if x in another_list:
        string_text = "String found"
    else:
        string_text = "String not found"
print(string_text)

答案 3 :(得分:1)

for x in list_of_lists:
    if not any(animal in list_of_items for animal in ("cow", "cat"))
        print("Cat or Cow could not be found in list {}".format(x)