簡體   English   中英

Python 3 中的這些 for 循環是否有更有效的方法?

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

我有以下所有從 1 到 8 的 for 循環。我想知道是否所有這些都可以只包含在 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

假設以下兩個條件:

  • 動作的執行順序無關緊要。
  • ActionX沒有副作用,不會導致將來調用BoolY給出不同的結果。

以下(雖然遠非漂亮)應該可以工作:


# 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

假設“更高效”,您的意思是“更快:需要分析實際用例以找出哪個版本的運行時間更短。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM