有没有更有效的方法来处理Python3中的for循环?

我有以下 for 循环,所有循环都从 1 到 8。我想知道是否所有这些都可以包含在 1 个 for 循环中。目前它不起作用的原因是因为如果您从 for 循环中断,那么它将退出所有 if 语句。

for i in range(1, 8):
    if Bool1(based on i):
        Action1
    else:
        break

for i in range(1, 8):
    if Bool2(based on i):
        Action2
    else:
        break

for i in range(1, 8):
    if Bool3(based on i):
        Action3
    else:
        break

for i in range(1, 8):
    if Bool4(based on i):
        Action4
    else:
        break

...

回答

你可以这样做:

tests_and_actions = [
    (Bool1, Action1),
    (Bool2, Action2),
    (Bool3, Action3),
    (Bool4, Action4),
    # ...
]

for test, action in tests_and_actions:
    for i in range(1, 8):
        if test(based on i):
            action()
        else:
            break

  • @Code-Apprentice The title and description are not descriptive enough it may mean "efficient to type". Anyway, there is no way to make code more efficient without knowing what it does. This is generic code.

以上是有没有更有效的方法来处理Python3中的for循环?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>