我有一个字符串列表:
animals = ["cat meow ", "dog bark"]
我想检查每个字符串是否包含单词
"cow"
这显然不存在于我上面的列表中。我正在尝试编写一个 if else 语句来检查我是否在列表的末尾以及是否找不到牛打印 "not found "
.下面的代码为每个不包含字符串的元素打印 not found 但我想在它的末尾迭代我的整个列表时只打印一次“not found”,但我不知道正确的语法。
animals = ['dog bark' , 'cat meow ']
for pet in animals:
if 'cow' in pet:
print('found')
else:
print('not found')
最佳答案
这对于 Python 的 any() 来说似乎是一个很好的用例。函数,返回 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')
关于python - 遍历列表并检查我是否在列表末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62447710/