Python 如果列出列表中没有的项目,则

Python 如果列出列表中没有的项目,则,python,list,if-statement,Python,List,If Statement,所以我想知道是否有一种更“漂亮”的方法来做到这一点。 目前我有一千多个列表,每个列表都是这样的: list_of_items = ["dog", "mouse", "cow", "goat", "fish"] 有些列表包含其他动物/字符串,但没有上述内容。视情况而定 我现在要发表一项国际单项体育联合会声明,其中说: list_of_items = ["dog", "mouse", "cow", "goat", "fish"] for x in list_of_items: if "co

所以我想知道是否有一种更“漂亮”的方法来做到这一点。 目前我有一千多个列表,每个列表都是这样的:

list_of_items = ["dog", "mouse", "cow", "goat", "fish"]
有些列表包含其他动物/字符串,但没有上述内容。视情况而定

我现在要发表一项国际单项体育联合会声明,其中说:

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”,则不会打印任何内容。但如果两者都找不到,则会出现print语句


我的问题是,我有几个“牛”、“猫”,因此我需要在if语句中包含它们。如果我有10个,作为一个例子,它会变得很长很难看。因此,有没有什么方法可以说:
如果动物列表不在动物列表项中:
,其中
动物列表
将只是一个字符串列表,应该包含在
语句中?

您可以将列表转换为
集合
,并使用
发行集

Ex:

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

if toCheck.issubset(list_of_items):
    print("Ok")
按注释编辑


如果你想让他们中的任何一个匹配的话,也许是这样的

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

a = ["dog", "mouse", "cow", "goat", "fish"]
b = ["cat", "cow"]
if(any(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

如果希望两者匹配,则:

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

a = ["dog", "mouse", "cow", "goat", "fish"]
b = ["cat", "cow"]
if(any(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

尝试以下操作:

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)

为什么循环是这样的?打印x是什么意思?打印时显示的是or,而条件显示的是and,这不是列表的超级直接。你能改用吗?我会用
set
s来做这类事情。如果你想要更强大的东西,我建议你看看pandas DataFrame,这正是我现在正在做的,除了改用
之外。但正如我所说的,若我突然要检查两个以上的字符串,那个么if语句将相当长,看起来不太好看。这就是我想要改进的地方,比如说,我有10个字符串需要检查。@DenverDang,好的,我会尝试修复it@DenverDang,现在可以了吗?但是,据我所知,这里的问题是,如果两个字符串都在列表中,这看起来像是什么?在我的情况下,我只需要他们中的一个在它应该是“Ok”之前到那里。所以,如果“牛”或“猫”在那里,它是好的。如果两者都是,那也不错。还有,这个toCheck语句是否有相反的版本?因为在运行这个时,我需要知道哪些列表没有这些项。因此,与其查看+1000打印输出以查看哪一个不存在,不如只查看说明不起作用的打印输出更容易。在这种情况下,您需要在检查条件中使用
,对吗?无论如何..更新了代码段,使用
any