Python 仅从for循环打印一次消息

Python 仅从for循环打印一次消息,python,for-loop,Python,For Loop,我想知道一个特定的字符串是否包含在列表的元素中。如果找到字符串,我想打印“字符串已找到”,否则“字符串未找到”。 但是,我提出的代码会多次打印“未找到字符串”。我知道原因,但我不知道如何修复它并只打印一次其中一条消息 animals=["dog.mouse.cow","horse.tiger.monkey", "badger.lion.chimp","trok.cat. bee"] for i in animals : if "cat" i

我想知道一个特定的字符串是否包含在列表的元素中。如果找到字符串,我想打印“字符串已找到”,否则“字符串未找到”。 但是,我提出的代码会多次打印“未找到字符串”。我知道原因,但我不知道如何修复它并只打印一次其中一条消息

animals=["dog.mouse.cow","horse.tiger.monkey",
         "badger.lion.chimp","trok.cat.    bee"]
      for i in animals :
          if "cat" in i:
              print("String found")
          else:
              print("String not found")

~

找到字符串时,在
if
块中添加
break
语句,并将
else
移动为for循环的
else
。在这种情况下,如果找到字符串,则循环将中断,并且永远不会到达else;如果循环未停止,则将到达else,并且将打印
“未找到字符串”

for i in animals:
    if 'cat' in i:
        print('String found')
        break
else:
    print('String not found')
您还可以使用:

演示:


在一行中有一个较短的方法来完成此操作。:)


这取决于这样一个事实,即如果列表中的每个项目都为False,sum将返回0,否则将返回正数(True)。

any
对于传递给它的iterable中的任何
x
,返回
True
if
bool(x)
is
True
。在这种情况下,a中的生成器表达式
“cat”表示a中的动物
。它检查
“cat”
是否包含在列表
动物
中的任何元素中。这种方法的优点是在所有情况下都不需要遍历整个列表


这是行不通的。如果“cat”出现在列表的最后一个元素,您仍然会多次打印“String not found”。@arditslce抱歉我的错误修复了它。您可能需要将If更改为:
如果i.split中的“cat”(“.”:
(假设动物中的所有字符串都以“.”分隔),否则,例如
“caterpiller.dog”
将返回True。我不确定这是否是你想要的行为。@Jdog被很好地发现了。然而,这在我的情况下不是问题。
任何
可能比
总和
更可取,尽管结果是一样的。。。当然编辑解决方案以包含您的改进
next(("String found" for animal in animals if "cat" in animal), "String not found")
>>> animals=["dog.mouse.cow","horse.tiger.monkey","badger.lion.chimp","trok.cat.    bee"]
>>> next(("String found" for animal in animals if "cat" in animal), "String not found")
'String found'
>>> animals=["dog.mouse.cow","horse.tiger.monkey"]
>>> next(("String found" for animal in animals if "cat" in animal), "String not found")
'String not found'
>>> animals=["dog.mouse.cow","horse.tiger.monkey","badger.lion.chimp","trok.cat.    bee"]
>>> print "Found" if any(["cat" in x for x in animals]) else "Not found"
Found
>>> animals = ["foo", "bar"]
>>> print "Found" if any(["cat" in x for x in animals]) else "Not found"
Not found
if any("cat" in a for a in animals):
    print "String found"
else:
    print "String not found"