简体   繁体   English

当循环在Python中运行到最后时,如何创建一个for循环,其中变量的值等于范围的停止值?

[英]How do I create a for-loop where the variable's value is equal to the stop value of range when the loop runs to the end in Python?

I'm having a conceptual problem porting this from C to Python: 我有一个概念上的问题从C移植到Python:

int p;
for (p = 32; p < 64; p += 2) {
    if (some condition)
        break;
    do some stuff
}
return p;

Converting the loop to for p in range(32,64,2) does not work. 将循环转换for p in range(32,64,2)不起作用。 This is because after the loop ends, p is equal 62 instead of 64. 这是因为在循环结束后, p等于62而不是64。

I can do it with a while loop easily: 我可以轻松地使用while循环:

p = 32
while p < 64:
    if (some condition):
        break
    do some stuff
    p += 2
return p

But I'm looking for a Pythonic way . 但我正在寻找一种Pythonic方式

you can use else for for loop in case condition isn't met to add 2 like C loop does: 你可以使用else for for循环,如果不满足条件,就像C循环那样添加2:

for p in range(32, 64, 2):
   if some_condition:
       break
else:
    # only executed if for loop iterates to the end
    p += 2

Extend the range, but include a second "redundant" break condition. 扩展范围,但包括第二个“冗余”中断条件。

for p in range(32, 65, 2):
    if p >= 64 or (some condition):
        break
    # do stuff

(The only significant difference between this and Jean-François Fabre's answer is which piece of the logic you duplicate: testing if p is out of range, or incrementing p .) (这与Jean-FrançoisFabre的答案之间唯一的显着区别是你复制了哪一段逻辑:测试p是否超出范围,或增加p 。)

A variation of chepner's answer that avoids duplicating the test would be to use itertools.count : chepner的答案的一个变种,避免重复测试将使用itertools.count

import itertools

for p in itertools.count(32, 2):
    if p >= 64 or (some condition):
        break
    do some stuff
return p

although I think that might as well be: 虽然我认为这可能是:

p = 32
while True:
    if p >= 64 or (some condition):
        break
    do some stuff
    p += 2
return p

and as tobias_k pointed out, then is trivially transformed to: 正如tobias_k指出的那样,然后将其简单地转换为:

p = 32
while p < 64 and not (some condition):
    do some stuff
    p += 2
return p

which I personally think is clearer. 我个人认为更清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM