【问题标题】:What is the optimum way to implement 'modes' in a for loop in python? [closed]在 python 的 for 循环中实现“模式”的最佳方法是什么? [关闭]
【发布时间】:2021-11-19 04:38:04
【问题描述】:

我希望能够让 for 循环根据它所处的“模式”执行不同的代码,但以效率的名义不必在每次迭代时检查此模式。如果您允许这些检查,则很容易做到这一点:

for i in range(n):
    if m == 0:
        # execute some code, test whether to update m
        continue
    if m == 1:
        # execute some other code, test whether to update m

但我想要的是,如果 for 循环保持其当前模式并继续运行,除非它被明确告知要更改它,以避免每次迭代时额外的“模式检查”步骤。

奇怪的是,我能想到的唯一方法是使用 goto 语句,我知道这不是答案!

i = 0

# start line for mode 1
# execute some code
i += 1
# test what mode to be in next, goto that line

# start line for mode 2
# execute some other code
i += 1
# test what mode to be in next, goto that line

# stop when you're at n

希望您能看到这两个理论程序实现了大致相同的目标,除非我以某种方式误解了。但是,第二个不必在每次 i 递增后测试其模式,因为测试接下来要处于哪种模式的动作也将它放在正确的位置以执行该模式的正确代码位。第一个运行测试并在一次迭代中更新 m,然后必须在下一次迭代中测试 m 以检查下一步要做什么。

认为我的理论是正确的,并且 a)这些事情是不同的,b)这应该是可能的(即您不需要进行“双重测试”)。如果是这样,我需要一些帮助,请在 python 中以一种简洁的方式实现它。

【问题讨论】:

    标签: python loops optimization


    【解决方案1】:

    您应该首先询问这是有意义的优化,还是毫无意义的微优化。如果您的分析表明检查模式花费了大量时间,您可以避免使用大致如下结构的代码:

    while True:
        if m == 0:
            while True:
                # Do stuff here
                # Run `break` when the mode changes
                pass
        elif m == 1:
            while True:
                # Do stuff here
                # Run `break` when the mode changes
                pass
    

    循环可以是任何类型 - 适合您的需要。我还建议将 if 语句下的代码块提取到返回而不是中断的函数中:

    def do_mode_0_stuff():
        while True:
            # Do stuff here
            # Run `return` when the mode changes
            pass
    
    def do_mode_1_stuff():
        while True:
            # Do stuff here
            # Run `return` when the mode changes
            pass
    
    while True:
        if m == 0:
            do_mode_0_stuff()
        elif m == 1:
            do_mode_1_stuff()
    

    最后,我非常怀疑这种重组是否会带来任何显着的性能改进,所以我会选择最清晰、优雅和可维护的任何结构。

    【讨论】:

    • 谢谢,这真的很有帮助。我不完全确定问题为何被关闭,但无论如何我都会接受这个答案。
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多