简体   繁体   English

使用for循环python的无限循环

[英]Infinite loop using a for loop python

So I'm trying to make a infinite loop that uses a for loop instead of a while loop. 因此,我试图制作一个使用for循环而不是while循环的无限循环。 This is my current code. 这是我当前的代码。 If this code works it should produce x infinitely. 如果此代码有效,则应无限产生x。 Current code: 当前代码:

z=1
for x in range(0,z):
    print(x)
    z=z+1

That doesn't work because the first time you enter the for loop the range function generates a range from zero to the value of z at that point, and later changes to z does not affect it. 那是行不通的,因为第一次进入for循环时, range函数会在该点生成一个从零到z值的范围,以后再更改z不会对其产生影响。 You can do something like what you want using, for example, itertools.count : 您可以使用itertools.count

from itertools import count

for x in count():
    print(x)

range returns an iterator. range返回一个迭代器。 The iterator is already generated and evaluated before the loop iteration. 在循环迭代之前已经生成并评估了迭代器。 (It's the returned iterator on which the loop is iterating). (这是循环所返回的迭代器)。

The value of z is not used after the iterator is returned hence incrementing or changing its value is no-op. z的值在返回迭代器后不再使用,因此增加或更改其值是no-op。

If you really want an infinite loop using for you will have to write your custom generator. 如果您真的想使用无限循环for则必须编写自定义生成器。

For eg: 例如:

def InfiniteLoop():
   yield  1

To be used as : 用作:

for i in InfiniteLoop()

Update list after each iteration make infinite loop 每次迭代后更新列表进行无限循环

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM