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

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

问题描述

我的问题很简单.

for 循环是否每次都评估它使用的参数?

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

例如:

for i in range(300):

python 是否为这个循环的每次迭代创建一个包含 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)):

是每次都应用反向过程,还是每次迭代都计算长度?(我对python2和python3都问这个)

Is the reverse process applied every single time, or the length calculated at every iteration? (I ask this for both python2 and python3)

如果不是,Python 如何在迭代时评估可迭代对象的变化?

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 ...

请注意,它不是完全等价的,因为 break 的工作方式不同.请记住,您可以将 else 添加到 for 循环中,但这在上面的代码中不起作用.

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天全站免登陆