Looping from 1 to infinity in Python

百般思念 提交于 2020-01-18 15:48:25

问题


In C, I would do this:

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

How can I achieve something similar in Python?


回答1:


Using itertools.count:

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

In Python2 xrange() is limited to sys.maxint, which may be enough for most practical purposes:

import sys
for i in xrange(sys.maxint):
    if there_is_a_reason_to_break(i):
        break

In Python3, 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().




回答2:


def to_infinity():
    index=0
    while 1:
        yield index
        index += 1

for i in to_infinity():
    if i > 10:break



回答3:


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.




回答4:


Simplest and best:

i = 0
while not there_is_reason_to_break(i):
    # some code here
    i += 1

It may be tempting to choose the closest analogy to the C code possible in Python:

from itertools import count

for i in count():
    if thereIsAReasonToBreak(i):
        break

But beware, modifying i will not effect the flow of the loop as it would in C. Therefore, using a while loop is actually a more appropriate choice for porting that C code to Python.




回答5:


def infinity():
    i=0
    while True:
        i+=1
        yield i


for i in infinity():
    if there_is_a_reason_to_break(i):
        break



回答6:


If you're doing that in C, then your judgement there is as cloudy as it would be in Python :-)

The better C way would be:

int i = 0;
while (! thereIsAReasonToBreak (i)) {
    // do something
    i++;
}

or:

int i;  // *may* be better inside the for statement to localise scope
for (i = 0; ! thereIsAReasonToBreak (i); i++) {
    // do something
}

That would translate to the Python:

i = 0
while not thereIsAReasonToBreak (i):
    # do something
    i += 1

Only if you need to exit in the middle of the loop somewhere would you need to worry about breaking. If your potential exit is at the start of the loop (as it appears to be here), it's usually better to encode the exit into the loop itself.




回答7:


Probably the best solution to this is to use a while loop: i=1 while True: if condition: break ...........rest code i+=1




回答8:


If you need to specify your preferred step size (like with range) and you would prefer not to have to import an external package (like itertools),

def infn(start=0, step_size=1):
    """Infinitely generate ascending numbers"""
    while True:
        yield start
        start += step_size

for n in infn():
    print(n)



回答9:


a = 1
while a:
    if a == Thereisareasontobreak(a):
        break
    a += 1



回答10:


while 1==1:  
    if want_to_break==yes:  
       break  
    else:
       # whatever you want to loop to infinity  

This loop with go indefinitely.




回答11:


You can also do the following way:

list=[0] for x in list:
    list.append(x+1)
    print x

This will result in an infinite for loop.



来源:https://stackoverflow.com/questions/9884213/looping-from-1-to-infinity-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!