python - 如何使用函数跳出 for 循环?

我正在使用 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/

相关文章:

r - 合并和删除*文件之间的冗余行

flutter - 为什么我们应该在 dart 中使用 static 关键字代替抽象?

github - 如何在两个句子之间添加 Git Readme 中的 Tab 空格?

python - 在 Python 中获取 Windows 版本

javascript - typescript :为什么我们不能为泛型类型分配默认值?

python - 如何在 Python 中将月份名称生成为列表?

regex - 为电话号码编写正则表达式

database - 使用golang从postgres中的csv批量插入而不使用for循环

c++ - 在 C 和 C++ 中, "#"是什么意思?

c++ - 基本 ODR 违规 : member functions in . h 文件