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 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    是的,这是官方的:

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

    等。这些事情不能在循环之后简单消失。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看