我有一个字符串列表:
animals = ["cat meow ", "dog bark"]
我想检查每个字符串是否包含单词"cow"
,该单词显然不在上面的列表中。我正在尝试编写一条if else语句,该语句检查我是否在列表的末尾以及是否未找到cow打印"not found "
。
下面的代码不会为每个不包含字符串的元素打印,但是我想在其末尾遍历整个列表时只打印一次“ not found”,但我不知道正确的语法。
animals = ['dog bark' , 'cat meow ']
for pet in animals:
if 'cow' in pet:
print('found')
else:
print('not found')
答案 0 :(得分:6)
这似乎是Python的any()函数的一个好用例,如果可迭代项中的任何一项为true,则该函数将返回True
。
animals = ['dog bark' , 'cat meow ']
has_cow = any('cow' in a for a in animals)
print('found' if has_cow else 'not found')
但是,如果您非常想使用for
循环,则可以使用标志变量来跟踪是否在循环中找到了该项,或者可以利用Python真正奇怪的for-else构造(如果未中断循环,则执行else子句)。在十几年的Python编程中,我从未使用过for-else
,所以这实际上只是出于好奇,我强烈不鼓励这样做。但这确实可以解决这个特定问题!
for a in animals:
if 'cow' in a:
print('found')
break
else: # WTF!?! Don't do this, folks.
print('not found')
答案 1 :(得分:5)
animals = ['dog bark' , 'cat meow ']
print('found' if any('cow' in pet for pet in animals) else 'not found')
它也适用于变量;
result = 'found' if any('cow' in pet for pet in animals) else 'not found'
答案 2 :(得分:1)
在这种情况下该标志很方便
flag = False
animals = ['dog bark' , 'cat meow']
for pet in animals:
if 'cow' in pet:
print("Found")
flag = True
if flag == False:
print("Not found")
它将打印"Not Found"
对于animals = ['dog bark', 'cat meow', "cow moo"]
,它将打印"Found"
。
答案 3 :(得分:1)
大多数编程语言允许 else 语句和 if 条件语句 一起使用。但是,在Python中, else 语句也可以与 for 循环一起使用,我们大多数人都不熟悉。通常,当我们搜索商品时, for / else 用于运行循环。例如:
lis=[1,2,3]
for i in lis:
if i==1:
print("1 found in list.")
break
else:
print("1 is not in list.")
此代码将打印:1 found in list.
循环运行时, i 会获取列表中的值,并且 if 语句将检查提供的条件,如果条件为true,则将执行print语句。之后,执行 break 语句,从而 break 代码中的控制流。触发某些条件时,Python中的 Break 语句用于将控制带出循环。
因此问题中的代码可以正确地写为:
animals=["dog bark","cat meow"]
for pet in animals:
if 'cow' in pet:
print("Found")
break'
else:
print("not found")
这将打印出所需的结果!
希望有帮助!
答案 4 :(得分:0)
您可以通过
来将未找到的打印件打印一次。animals = ['dog bark' , 'cat meow ']
for i, pet in enumerate(animals):
if 'cow' in pet:
print('found')
break
elif i+1 == len(animals):
print('not found')
或一行
print("found" if [i for i in animals if "cow" in i] else "not found")
此代码将打印找到的代码,如果其中一头有母牛,它将退出循环,它将检入母牛的最后一项,而不是该项目,然后打印“未找到”。