for循环如何评估它的参数 [英] How does a for loop evaluate its argument

查看:133
本文介绍了for循环如何评估它的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



对于循环,是否会计算每次使用的参数例如:

 我在范围内(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
...循环体...

请注意,这不是相当于,因为 break 会工作不同。请记住,您可以将 else 添加到循环的中,但是在上面的代码中不起作用。 / p>

My question is a very simple one.

Does a for loop evaluates the argument it uses every time ?

Such as:

for i in range(300):

Does python create a list of 300 items for every iteration of this loop?

If it is, is this a way to avoid it?

lst = range(300)
for i in lst:
    #loop body

Same goes for code examples like this.

for i in reversed(lst):

for k in range(len(lst)):

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:

it = iter(range(300))
while True:
    try:
        i = next(it)
    except StopIteration:
        break
    ... body of loop ...

Note that it's not quite equivalent, because break will work differently. Remember that you can add an else to a for loop, but that won't work in the above code.

这篇关于for循环如何评估它的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆