Python 中可能出现无限循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34253996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Infinite for loops possible in Python?
提问by Britni.M
Is it possible to get an infinite loop in for
loop?
是否有可能在for
循环中获得无限循环?
My guess is that there can be an infinite for loop in Python. I'd like to know this for future references.
我的猜测是 Python 中可以有一个无限的 for 循环。我想知道这一点以备将来参考。
回答by Jon
Yes, use a generator that always yields another number: Here is an example
是的,使用总是产生另一个数字的生成器:这是一个例子
def zero_to_infinity():
i = 0
while True:
yield i
i += 1
for x in zero_to_infinity():
print(x)
It is also possible to achieve this by mutating the list you're iterating on, for example:
也可以通过改变您正在迭代的列表来实现这一点,例如:
l = [1]
for x in l:
l.append(x + 1)
print(x)
回答by orokusaki
The quintessential example of an infinite loop in Python is:
Python 中无限循环的典型例子是:
while True:
pass
To apply this to a for loop, use a generator (simplest form):
要将其应用于 for 循环,请使用生成器(最简单的形式):
def infinity():
while True:
yield
This can be used as follows:
这可以按如下方式使用:
for _ in infinity():
pass
回答by Padraic Cunningham
To answer your question using a for loop as requested, this would loop forever as 1 will never be equal to 0:
要根据要求使用 for 循环回答您的问题,这将永远循环,因为 1 永远不会等于 0:
for _ in iter(int, 1):
pass
If you wanted an infinite loop using numbers that were incrementing as per the first answer you could use itertools.count
:
如果您想要使用按照第一个答案递增的数字进行无限循环,您可以使用itertools.count
:
from itertools import count
for i in count(0):
....
回答by Dleep
While there have been many answers with nice examples of how an infinite for loop can be done, none have answered why (it wasn't asked, though, but still...)
虽然有很多关于如何完成无限循环的很好例子的答案,但没有人回答为什么(虽然没有问,但仍然......)
A for loop in Python is syntactic sugar for handling the iterator object of an iterable an its methods. For example, this is your typical for loop:
Python 中的 for 循环是用于处理可迭代对象及其方法的迭代器对象的语法糖。例如,这是典型的 for 循环:
for element in iterable:
foo(element)
And this is what's sorta happening behind the scenes:
这就是幕后发生的事情:
iterator = iterable.__iter__()
try:
while True:
element = iterator.next()
foo(element)
except StopIteration:
pass
An iterator object has to have, as it can be seen, anext
method that returns an element and advances once (if it can, or else it raises a StopIteration exception).
可以看出,迭代器对象必须有一个next
方法,该方法返回一个元素并前进一次(如果可以,否则会引发 StopIteration 异常)。
So every iterable object of which iterator'snext
method does never raise said exception has an infinite for loop. For example:
因此,迭代器next
方法永远不会引发所述异常的每个可迭代对象都有一个无限循环。例如:
class InfLoopIter(object):
def __iter__(self):
return self # an iterator object must always have this
def next(self):
return None
class InfLoop(object):
def __iter__(self):
return InfLoopIter()
for i in InfLoop():
print "Hello World!" # infinite loop yay!
回答by Sudarshan
Using itertools.count:
import itertools
for i in itertools.count():
pass
In Python3, range() can go much higher, though not to infinity:
在 Python3 中, range() 可以更高,但不是无穷大:
import sys
for i in range(sys.maxsize**10): # you could go even higher if you really want but not infinity
pass
Another way can be
另一种方式可以是
def to_infinity():
index=0
while 1:
yield index
index += 1
for i in to_infinity():
pass
回答by Sudarshan
You can configure it to use a list. And append an element to the list everytime you iterate, so that it never ends.
您可以将其配置为使用列表。每次迭代时都将一个元素附加到列表中,这样它就永远不会结束。
Example:
例子:
list=[0]
t=1
for i in list:
list.append(i)
#do your thing.
#Example code.
if t<=0:
break
print(t)
t=t/10
This exact loop given above, won't get to infinity. But you can edit the if
statement to get infinite for
loop.
上面给出的这个精确循环不会达到无穷大。但是您可以编辑该if
语句以获得无限for
循环。
I know this may create some memory issues, but this is the best that I could come up with.
我知道这可能会造成一些内存问题,但这是我能想到的最好的方法。
回答by New Guy
Why not try itertools.count?
为什么不试试itertools.count?
import itertools
for i in itertools.count():
print i
which would just start printing numbers from 0 to ...
它将开始打印从 0 到 ...
Try it out.
试试看。
**I realize I'm a couple of years late but it might help someone else :)
**我意识到我迟到了几年,但它可能会帮助其他人:)
回答by sumit
my_list = range(10)
for i in my_list:
print ("hello python!!")
my_list.append(i)
回答by fizzybear
Here's another solution using the itertools
module.
这是使用该itertools
模块的另一个解决方案。
import itertools
for _ in itertools.repeat([]): # return an infinite iterator
pass