簡體   English   中英

從for循環僅打印一次消息

[英]Print out message only once from the for loop

我想查找列表元素內是否包含特定字符串。 如果找到了字符串,我想打印出“找到字符串”,否則要打印“找不到字符串”。 但是,我想到的代碼會多次打印“找不到字符串”。 我知道原因,但我不知道如何解決它,只打印其中一條消息。

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並打印'String not found'

for i in animals:
    if 'cat' in i:
        print('String found')
        break
else:
    print('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

這依賴於以下事實:如果列表中的每個項目均為False,sum將返回0,否則返回正數(True)。

如果bool(x)對於傳遞給它的可迭代對象中的任何xTrue ,則any返回True 在這種情況下,生成器"cat" in a for a in animals表示"cat" in a for a in animals 哪個檢查列表animals內的任何元素中是否包含"cat" 這種方法的優點是在所有情況下都不需要遍歷整個列表。

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

您還可以使用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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM