10

我想查找特定字符串是否包含在列表的元素中。如果找到字符串,我想打印出“String found”,否则“String not 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

4 回答 4

13

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

for i in animals:
    if 'cat' in i:
        print('String found')
        break
else:
    print('String not found')
于 2013-09-12T12:10:45.170 回答
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)。

于 2013-09-12T12:17:33.027 回答
2

anyTrue如果bool(x)是传递给它的可迭代True对象中的任何内容,则返回。x在这种情况下,生成器表达式"cat" in a for a in animals。它检查是否"cat"包含在 list 内的任何元素中animals这种方法的优点是在所有情况下都不需要遍历整个列表。

if any("cat" in a for a in animals):
    print "String found"
else:
    print "String not found"
于 2013-09-12T12:20:22.713 回答
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'
于 2013-09-12T12:11:32.067 回答