for循环如何评估它的参数 [英] How does a for loop evaluate its argument
问题描述
对于循环,
我在范围内(300) :
python是否为这个循环的每次迭代创建了300个项目列表?
如果是这样,这是避免它的方法吗?
lst = range 300)
for ist:
#loop body
这样的代码示例。
$ pre $ 对于我反转(lst):
对于范围内的k len(lst)):
每一次都应用相反的过程,迭代? (我要求python2和python3)
如果不是的话,Python如何在迭代的时候评估迭代器上的变化?
不用担心,迭代器只会被评估一次。它的结果大致相当于这样的代码:
it = iter(range(300))
while True :
try:
i = next(it)
除了StopIteration:
break
...循环体...
请注意,这不是相当于,因为 My question is a very simple one. Does a Such as: Does python create a list of 300 items for every iteration of this loop? If it is, is this a way to avoid it? Same goes for code examples like this. Is the reverse process applied every single time, or the length calculated at every iteration? (I ask this for both python2 and python3) If not, how does Python evaluate the changes on the iterable while iterating over it ? No fear, the iterator will only be evaluated once. It ends up being roughly equivalent to code like this: Note that it's not quite equivalent, because 这篇关于for循环如何评估它的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! break
会工作不同。请记住,您可以将 else
添加到循环的中,但是在上面的代码中不起作用。 / p>
for
loop evaluates the argument it uses every time ?for i in range(300):
lst = range(300)
for i in lst:
#loop body
for i in reversed(lst):
for k in range(len(lst)):
it = iter(range(300))
while True:
try:
i = next(it)
except StopIteration:
break
... body of loop ...
break
will work differently. Remember that you can add an else
to a for
loop, but that won't work in the above code.