Looping from 1 to infinity in Python

前端 未结 6 2182
日久生厌
日久生厌 2020-11-27 18:41

In C, I would do this:

int i;
for (i = 0;; i++)
  if (thereIsAReasonToBreak(i))
    break;

How can I achieve something similar in Python?

6条回答
  •  暖寄归人
    2020-11-27 19:30

    Reiterating thg435's comment:

    from itertools import takewhile, count
    
    def thereIsAReasonToContinue(i):
        return not thereIsAReasonToBreak(i)
    
    for i in takewhile(thereIsAReasonToContinue, count()):
        pass # or something else
    

    Or perhaps more concisely:

    from itertools import takewhile, count
    
    for i in takewhile(lambda x : not thereIsAReasonToBreak(x), count()):
        pass # or something else
    

    takewhile imitates a "well-behaved" C for loop: you have a continuation condition, but you have a generator instead of an arbitrary expression. There are things you can do in a C for loop that are "badly behaved", such as modifying i in the loop body. It's possible to imitate those too using takewhile, if the generator is a closure over some local variable i that you then mess with. In a way, defining that closure makes it especially obvious that you're doing something potentially confusing with your control structure.

提交回复
热议问题