i在范围(n)中的终止条件

mch*_*mch 0 python python-3.x

我必须使用一些现有的(很旧的)C库的几乎1:1的Python翻译,然后发现了问题。

原始代码为:

int i, n;
//...
for (i = 0; i < n; i++)
    if (someCondition(i))
        doSomething();
        break;
if (i == n)
    doSomeOtherStuff();
Run Code Online (Sandbox Code Playgroud)

它被翻译成

for i in range(n):
    if someCondition(i):
        doSomething()
        break
if i == n:
    doSomeOtherStuff()
Run Code Online (Sandbox Code Playgroud)

问题是如果永不为真,i则等于n - 1循环后someCondtion(i)

我的解决方案是

found = False
for i in range(n):
    if someCondition(i):
        doSomething()
        found = True
        break
if not found:
    doSomeOtherStuff()
Run Code Online (Sandbox Code Playgroud)

有更好的解决方案吗?我希望代码更改最少的解决方案仍然能够比较C和Python实现。Python代码仅用于测试,C实现是生产代码。因此,没有性能要求,只有可读性。

jon*_*rpe 6

Python for语句具有可选的else套件,如果项目用尽,则执行该套件,但如果您或其他原因提早退出循环,则不执行该套件break。因此,您可以将该代码编写为:

for i in range(n):
    if someCondition(i):
        doSomething()
        break
else:
    doSomeOtherStuff()
Run Code Online (Sandbox Code Playgroud)