简体   繁体   中英

Is there a more efficient way to these for loops in Python 3?

I have the following for loops all of which run from 1 to 8. I'm wondering if all of this can be encased in just 1 for loop. The reason it doesn't work at the moment is because if you break from the for loop then it would exit it for all if statements.

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

...

You can do this:

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

Assuming the following two conditions:

  • The order of execution of the actions does not matter.
  • ActionX does not have side effects that cause future calls to BoolY to give a different result.

The following (while far from beautiful) should work:


# Flags, indicating which part is still relevant
active1 = True
active2 = True
active3 = True
active4 = True

for i in range(1, 8):

    if active1 and Bool1(based on i):
        Action1
    else:
        active1 = False

    if active2 and Bool2(based on i):
        Action2
    else:
        active2 = False

    ...

    # The below is just an optimization to avoid superfluous looping.
    if not active1 and not active2 and not active3 and not active4:
        break

Assuming with "more efficient", you mean "faster: One would need to profile the actual use-case to find out which version has the smaller run time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM