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

时间:2013-09-12 12:09:29

标签: python for-loop

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

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")

4 个答案:

答案 0 :(得分:9)

找到字符串时在break块中添加if语句,并将else移动到for循环的else。如果是这种情况,如果找到了字符串,则循环将中断并且永远不会到达else,如果循环没有制动,则将到达else,并且将打印'String not found'

for i in animals:
    if 'cat' in i:
        print('String found')
        break
else:
    print('String not found')

答案 1 :(得分:3)

在一行中执行此操作的方法较短。 :)

>>> 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

这依赖于如果列表中的每个项都为False则sum将返回0的事实,否则将返回正数(True)。

答案 2 :(得分:2)

如果传递给它的iterable中的any Truebool(x),则

True会返回x。在这种情况下,生成器表达式"cat" in a for a in animals。哪个检查列表"cat"中的任何元素中是否包含animals。此方法的优点是无需遍历所有情况下的整个列表。

if any("cat" in a for a in animals):
    print "String found"
else:
    print "String not found"

答案 3 :(得分:1)

您还可以使用next()

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'