Looping from 1 to infinity in Python

2020-01-27 03:58发布

In C, I would do this:

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

How can I achieve something similar in Python?

标签: python loops
11条回答
祖国的老花朵
2楼-- · 2020-01-27 04:28

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.

查看更多
Deceive 欺骗
3楼-- · 2020-01-27 04:28
def infinity():
    i=0
    while True:
        i+=1
        yield i


for i in infinity():
    if there_is_a_reason_to_break(i):
        break
查看更多
贪生不怕死
4楼-- · 2020-01-27 04:32
def to_infinity():
    index=0
    while 1:
        yield index
        index += 1

for i in to_infinity():
    if i > 10:break
查看更多
我只想做你的唯一
5楼-- · 2020-01-27 04:33

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.

查看更多
做自己的国王
6楼-- · 2020-01-27 04:36

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楼-- · 2020-01-27 04:39

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.

查看更多
登录 后发表回答