Looping from 1 to infinity in Python

前端 未结 6 2190
日久生厌
日久生厌 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:32

    Using itertools.count:

    import itertools
    for i in itertools.count(start=1):
        if there_is_a_reason_to_break(i):
            break
    

    In Python 2, range() and xrange() were limited to sys.maxsize. In Python 3 range() can go much higher, though not to infinity:

    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
    

    So it's probably best to use count().

提交回复
热议问题