[英]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?
我有一个概念上的问题从C移植到Python:
int p;
for (p = 32; p < 64; p += 2) {
if (some condition)
break;
do some stuff
}
return p;
将循环转换for p in range(32,64,2)
不起作用。 这是因为在循环结束后, p
等于62而不是64。
我可以轻松地使用while
循环:
p = 32
while p < 64:
if (some condition):
break
do some stuff
p += 2
return p
但我正在寻找一种Pythonic方式 。
你可以使用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
扩展范围,但包括第二个“冗余”中断条件。
for p in range(32, 65, 2):
if p >= 64 or (some condition):
break
# do stuff
(这与Jean-FrançoisFabre的答案之间唯一的显着区别是你复制了哪一段逻辑:测试p
是否超出范围,或增加p
。)
chepner的答案的一个变种,避免重复测试将使用itertools.count
:
import itertools
for p in itertools.count(32, 2):
if p >= 64 or (some condition):
break
do some stuff
return p
虽然我认为这可能是:
p = 32
while True:
if p >= 64 or (some condition):
break
do some stuff
p += 2
return p
正如tobias_k指出的那样,然后将其简单地转换为:
p = 32
while p < 64 and not (some condition):
do some stuff
p += 2
return p
我个人认为更清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.