在C中,我会这样做:
int i;
for (i = 0;; i++)
if (thereIsAReasonToBreak(i))
break;
Run Code Online (Sandbox Code Playgroud)
如何在Python中实现类似的功能?
Joh*_*ooy 103
import itertools
for i in itertools.count():
if there_is_a_reason_to_break(i):
break
Run Code Online (Sandbox Code Playgroud)
在Python2 xrange()中仅限于sys.maxint,这可能足以满足大多数实际需要:
import sys
for i in xrange(sys.maxint):
if there_is_a_reason_to_break(i):
break
Run Code Online (Sandbox Code Playgroud)
在Python3中,range()可以更高,但不是无限:
import sys
for i in range(sys.maxsize**10): # you could go even higher if you really want
if there_is_a_reason_to_break(i):
break
Run Code Online (Sandbox Code Playgroud)
所以最好使用它count().
spi*_*igo 13
def to_infinity():
index=0
while 1:
yield index
index += 1
for i in to_infinity():
if i > 10:break
Run Code Online (Sandbox Code Playgroud)
wim*_*wim 12
最简单和最好的:
i = 0
while not there_is_reason_to_break(i):
# some code here
i += 1
Run Code Online (Sandbox Code Playgroud)
选择最接近 Python 中 C 代码的类比可能很诱人:
from itertools import count
for i in count():
if thereIsAReasonToBreak(i):
break
Run Code Online (Sandbox Code Playgroud)
但要注意,修改i不会像在 C 中那样影响循环的流程。因此,使用while循环实际上是将 C 代码移植到 Python 的更合适的选择。
如果您想使用循环for,可以组合内置函数iter(另请参阅此答案)和具有计数器的enumerate无限循环。for我们用来iter创建一个无限迭代器并enumerate提供计数循环变量。默认情况下,起始值为零,但您可以使用start参数设置不同的起始值。
for i, _ in enumerate(iter(bool, True), start=1):
input(i)
Run Code Online (Sandbox Code Playgroud)
哪个打印:
1
2
3
4
5
...
Run Code Online (Sandbox Code Playgroud)
重申 thg435 的评论:
from itertools import takewhile, count
def thereIsAReasonToContinue(i):
return not thereIsAReasonToBreak(i)
for i in takewhile(thereIsAReasonToContinue, count()):
pass # or something else
Run Code Online (Sandbox Code Playgroud)
或者也许更简洁:
from itertools import takewhile, count
for i in takewhile(lambda x : not thereIsAReasonToBreak(x), count()):
pass # or something else
Run Code Online (Sandbox Code Playgroud)
takewhile模仿“行为良好”的 C for 循环:您有一个延续条件,但您有一个生成器而不是任意表达式。您可以在 C for 循环中执行一些“行为不当”的操作,例如i在循环体中进行修改。takewhile如果生成器是某个局部变量的闭包,那么您也可以使用 来模仿它们i。在某种程度上,定义该闭包使得您正在做的事情特别明显,可能会与您的控制结构混淆。