python是否正式支持在循环后重用循环变量?
发布于 2021-01-29 17:33:22
以下代码是不好的做法吗?
for i in some_values:
do_whatever(i)
do_more_things(i)
不知何故,我觉得该变量i
应保留在for循环内的块范围内。但是python 2.7让我在循环后可以重用它。
python是否正式支持该功能,还是我在滥用该语言?
关注者
0
被浏览
42
1 个回答
-
是的,这是官方的:
for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] > The target list is not deleted when the loop is finished
http://docs.python.org/reference/compound_stmts.html#for
请注意,后面的目标列表
for
远不只是变量:for some_list[blah] in... for some_object.foo in... for a[:n] in ...:
等。这些事情不能在循环之后简单消失。