这段代码生成排列,我感兴趣的是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
已由 else
处理.
当我删除else: return
时,该函数以重复的方式无限地生成排列。
我想知道这一点,因为我需要在 C++ 中复制此代码。
任何帮助或建议将不胜感激:)
最佳答案
for 循环的 else
子句在特殊情况下运行:如果循环在没有任何中断的情况下完成(在本例中为:break
),则 else
子句将运行,否则将被跳过。
也就是说,如果执行了与if
相关的else
,则for
的else
将不会运行。
关于Python 3 'else' 在这个循环中如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58774957/