Python 从 for 循环中只打印一次消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18763905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:45:01  来源:igfitidea点击:

Print out message only once from the for loop

pythonfor-loop

提问by multigoodverse

I want to find if a specific string is contained inside the elements of a list. If the string is found, I want to print out "String found", otherwise "String not found". But, the code I came up with, makes multiple prints of "String not found". I know the reason why, but I don't know how to fix it and print it only one of the messages once.

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

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

~

~

采纳答案by Viktor Kerkez

Add a breakstatement in the ifblock when the string is found, and move the elseto be the elseof the for loop. If this case if the string is found the loop will break and the else will never be reached, and if the loop doesn't brake the else will be reached and 'String not found'will be printed.

当找到字符串时breakif块中添加一条语句,并将 移动elseelsefor 循环的 。如果在这种情况下找到字符串,则循环将中断并且永远不会到达 else,如果循环没有中断,则将到达 else'String not found'并将被打印。

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

回答by alecxe

You can also use next():

您还可以使用next()

next(("String found" for animal in animals if "cat" in animal), "String not found")

DEMO:

演示:

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

回答by Maria Zverina

There is a shorter way to do this in one line. :)

有一种更短的方法可以在一行中做到这一点。:)

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

This relies on the fact that sum will return 0 if every item in the list is False, and will return positive number (True) otherwise.

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

回答by HennyH

anyreturns Trueif bool(x)is Truefor any xin the iterable passed to it. In this case the generator expression "cat" in a for a in animals. Which checks if "cat"is contained within any of the elements inside the list animals. This method has the advantage of not needing to traverse the whole list in allcases.

any返回Trueif bool(x)is Truefor any xin iterable 传递给它。在这种情况下,生成器表达式"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"