为什么Python不在循环后删除iterate变量?

2024-05-14 09:39:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在运行ipython时发现了这种情况。python的版本是2.6.6和ipython 0.13。例如:

In [1]: for i in range(100):
   ...:     pass
   ...: 

In [2]: who
Out [2]: i  

In [3]: print i
Out [3]: 99

循环之后,变量i仍然存在。所以我想知道这是Python设计的缺陷吗?如果没有,为什么?谢谢。在


Tags: in版本foripython情况rangepassout
1条回答
网友
1楼 · 发布于 2024-05-14 09:39:26

不是虫子。在

for循环不创建新的作用域。只有函数和模块才引入了一个新的作用域,类、list/dict/set comprehensions*、lambdas和generator是作用域界定的专用函数。在

这在^{} loop statement documentation中有记录:

The target list is not deleted when the loop is finished, but if the sequence is empty, it will not have been assigned to at all by the loop.

此功能的实际用途是getting the last item of an iterable

last = defaultvalue
for last in my_iter:
    pass

python2中的List comprehension的工作方式类似于for循环,没有新的作用域,但是在python3中,它们以及跨Python版本的dict和set理解都会创建一个新的作用域。在

相关问题 更多 >

    热门问题