【发布时间】:2026-01-30 18:40:01
【问题描述】:
有一个类似的列表
lst = ['hello', 'stack', 'overflow', 'friends']
我该怎么做:
if there is not an element in lst starting with 'p=' return False else return True
?
我在想这样的事情:
for i in lst:
if i.startswith('p=')
return True
但我不能在循环内添加 return False,否则它会在第一个元素处消失。
【问题讨论】:
-
@ScottHunter 确定
-
既然你只知道它是
False,一旦你测试了所有元素,你应该在循环结束后返回False。 -
然后将
return False放在 循环之外,或者放在else块中。你不能确定没有,直到最后。或者只使用return any(...)。