2024-05-14 09:39:26 发布
网友
我在运行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设计的缺陷吗?如果没有,为什么?谢谢。在
i
不是虫子。在
for循环不创建新的作用域。只有函数和模块才引入了一个新的作用域,类、list/dict/set comprehensions*、lambdas和generator是作用域界定的专用函数。在
for
这在^{} 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理解都会创建一个新的作用域。在
不是虫子。在
for
循环不创建新的作用域。只有函数和模块才引入了一个新的作用域,类、list/dict/set comprehensions*、lambdas和generator是作用域界定的专用函数。在这在^{} loop statement documentation 中有记录:
此功能的实际用途是getting the last item of an iterable:
python2中的List comprehension的工作方式类似于
for
循环,没有新的作用域,但是在python3中,它们以及跨Python版本的dict和set理解都会创建一个新的作用域。在相关问题 更多 >
编程相关推荐