Python 中是否有一种优雅的方法来检测中断条件是在最后 迭代时出现还是从不 出现?
C++ 示例:
int k, n = 10;
for (k = 0; k < n; k++)
if (condition) break;
if (k == n) cout << "Never broke\n";
else cout << "Broke at " << k << '\n';
Python 示例:
n = 10
for k in range(n):
if condition: break
if k == n: print("Never broke")
else: print("Broke at", k)
在 Python 中,我们不知道 condition
在最后一次迭代中是否为真,因为在这两种情况下 k 都是 9。
为什么不直接使用 range(n + 1)
呢?因为在某些情况下,当 k 为 n 时,我们可能会遇到“索引超出范围”错误。
一种可能的解决方法是使用如下所示的标记值,但是否有更好的方法?
n, flag = 10, True
for k in range(n):
if condition:
flag = False
break
if flag: print("Never broke")
else: print("Broke at", k)
最佳答案
使用for
/else
。这正是它的用途。
for k in range(n):
if condition:
print("Broke at", k)
break
else:
print("Never broke")
关于python - 检查中断条件是否被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47784197/