遍历列表并检查我是否在列表末尾

Vas*_*tos 3 python for-loop list

我有一个字符串列表:

animals = ["cat meow ", "dog bark"]
Run Code Online (Sandbox Code Playgroud)

我想检查每个字符串是否包含"cow"在我上面的列表中显然不存在的单词。我正在尝试编写一个 if else 语句来检查我是否在列表的末尾以及是否找不到 cow 打印"not found "

下面的代码为每个不包含字符串的元素打印 not found 但我想在它的末尾迭代整个列表时只打印一次“not found”,但我不知道正确的语法。

animals = ['dog bark' , 'cat meow ']
for pet in animals:
  if 'cow' in pet:
    print('found')
  else:
    print('not  found') 
Run Code Online (Sandbox Code Playgroud)

FMc*_*FMc 6

这似乎是 Python 的any()函数的一个很好的用例,True如果迭代中的任何项目为真,它就会返回。

animals = ['dog bark' , 'cat meow ']
has_cow = any('cow' in a for a in animals)
print('found' if has_cow else 'not found')
Run Code Online (Sandbox Code Playgroud)

但是,如果您非常渴望使用for循环,则可以使用标志变量来跟踪是否在循环中找到了该项目,或者利用 Python 真正奇怪的for-else构造(如果循环是不破)。在十几年的 Python 编程中,我从未使用过for-else,所以它真的只是一种语言好奇心,我强烈反对它。但它确实适用于这个特定问题!

for a in animals:
    if 'cow' in a:
        print('found')
        break
else:                      # WTF!?!  Don't do this, folks.
    print('not found')
Run Code Online (Sandbox Code Playgroud)


Sy *_*Ker 5

animals = ['dog bark' , 'cat meow ']

print('found' if any('cow' in pet for pet in animals) else 'not found')
Run Code Online (Sandbox Code Playgroud)

它也适用于变量;

result = 'found' if any('cow' in pet for pet in animals) else 'not found'
Run Code Online (Sandbox Code Playgroud)