我正在使用 for 循环运行在元素列表的函数中定义的 if 操作。在第一个 Action 中有一个次要 Action 。我希望 for 循环在第一次操作成功后停止。下面是示例代码来演示:
my_list = [99, 101, 200, 5, 10, 20, 40]
def action(x):
if x >= 100:
print('It is finished')
over_100 = True
return over_100
def action2(x):
x += 1
action(x)
over_100 = False
for number in my_list:
action2(number)
if over_100:
break
我希望 for 循环在 >=100 的第一个实例处停止。例如,它应该将 1 加到 99(列表的第一个元素),然后停止所有操作。相反,它会打印 3 次“It is finished”,因为它会遍历整个列表。
最佳答案
您可以让函数返回一个值并在循环中检查该值。您可以使用 break
来跳出循环。
list_of_scopes = [scope1, scope2, scope3, etc.)
def action_function():
return 'TEST' in xxxxx
for scope in list_of_scopes:
found = action_function()
if found:
break
从 Python 3.8
开始,您甚至可以使用 walrus 运算符来提高代码的可读性:
for scope in list_of_scopes:
if found := action_function():
# optionally do something with `found`
break
https://stackoverflow.com/questions/66522597/