简体   繁体   English

Python for循环 - 为什么这不是无限循环?

[英]Python for loop - why does this not infinite loop?

Consider the following snippet of Python code: 考虑以下Python代码片段:

x = 14
for k in range(x):
    x += 1

At the end of execution, x is equal to 28. 在执行结束时, x等于28。

My question: shouldn't this code loop forever? 我的问题:这段代码不应该永远循环吗? At each iteration, it checks if k is less than x . 在每次迭代时,它检查k是否小于x However, x is incremented within the for loop, so it has a higher value for the next comparison. 但是, x在for循环中递增,因此它具有较高的值用于下一次比较。

range(x) is not a "command". range(x)不是“命令”。 It creates a range object one time, and the loop iterates over that. 它创建一个范围对象,循环遍历该范围。 Changing x does not change all objects that were made using it. 更改x不会更改使用它创建的所有对象。

>>> x = 2
>>> k = range(x)
>>> list(k)
[0, 1]
>>> x += 1
>>> list(k)
[0, 1]

no, range(x) will return a list with the items[0,1,2,3,4,5,6,7,8,9,10,11,12,13] these items will be iterated. 不, range(x)将返回带有[0,1,2,3,4,5,6,7,8,9,10,11,12,13]项的列表,这些项将被迭代。 Each time that the loop body gets evaluated x's value change but this does not affects the list that was already generate. 每次循环体被评估时x的值都会发生变化,但这不会影响已经生成的列表。

in other words the collection that you will be iterating will be generated only one time. 换句话说,您将迭代的集合将只生成一次。

It's because python for in loop have different behavior compared to for (in other languages): range(x) is not executed in every iteration, but at first time, and then for in iterate across its elements. 这是因为for in循环中的python与for (在其他语言中)相比具有不同的行为: range(x)不是在每次迭代中执行,而是在第一次执行,然后在其元素for in迭代。 If you want to change the code to run an infinite loop you can use a while instead (and in that case range(x) is pointless). 如果你想改变代码来运行无限循环,你可以使用一段while (在这种情况下,范围(x)是没有意义的)。

The for loop in python is not an iterator, but rather iterates over a sequence / generator ie any form of iterable . python中的for循环不是迭代器,而是迭代序列/生成器,即任何形式的iterable

Considering this, unless the iterable is infinite, the loop will not be infinite. 考虑到这一点,除非迭代是无限的,否则循环将不是无限的。 A sequence cannot be infinite but you can possibly create/utilite an infinite generator. 序列不能是无限的,但您可以创建/使用无限生成器。 One possibility is to use itertools.count which generates a non-ending sequence of numbers starting from a specified start with a specified interval. 一种可能性是使用itertools.count ,它从指定的开始处以指定的间隔开始生成非结束的数字序列。

from itertools import count        |  for(;;) {
for i in count(0):                 |      //An infinite block
    #An infinite block             |  }

Alternatively, you can always utilize while loop to create a classical infinite loop 或者,您始终可以使用while循环来创建经典的无限循环

while True:
     #An infinite block

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

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