Python 3“其他”在此循环中如何工作

这段代码生成了排列,我对最后的else: return的工作方式很感兴趣。

all_str = []
def permu(iterable,r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = list(range(n))
    cycles = list(range(n,n - r,-1))
    all_str.append( tuple(pool[i] for i in indices[:r]))
    while True:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i + 1:] + indices[i:i + 1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i],indices[-j] = indices[-j],indices[i]
                all_str.append( tuple(pool[i] for i in indices[:r]))
                break
        else: # here
            return
permu("abcde",4)

底部的else是什么意思?我知道您可以在循环中使用if,在循环中使用else,但这似乎并非如此,因为if已经由{ {1}}。

当我删除else时,该函数以重复的方式无休止地生成排列。

我想知道这一点,因为我需要用C ++复制此代码。

任何帮助或建议将不胜感激:)

yechuan09 回答:Python 3“其他”在此循环中如何工作

for循环的else子句在特殊情况下运行:如果循环结束而没有任何中断(在这种情况下为break),则else子句将运行,否则,它将被跳过。 即,如果执行了与else相关的if,则else中的for将不会运行。

,

如果没有人从for循环中明确执行else,则执行for循环的break语句 (python文档https://docs.python.org/3.6/reference/compound_stmts.html#the-for-statement中的完整说明)

所以如果您想在C ++中复制它 您必须设置一个变量,以跟踪是通过中断还是仅因为for循环结束退出了for循环。

我很久没有写C了,所以我的伪C代码中可能会有微小的错误。

while(bla){
  int encountered_break = 0;
  for(bla;bla;bla){
      if (bla){
      } else {
          encountered_break = 1;
          break;
      }
  }
  if(!encountered_break){
      return;
  }
}
,

更清楚地将for else读为for finally。如果else完成正确,则执行for loop。在您的示例中,它将在for loop完成后返回(退出一段时间)。

在您的示例中,如果删除else: return,则执行将始终在while True内部。

详细了解here

本文链接:https://www.f2er.com/3134614.html

大家都在问