在for循环之外使用for循环变量 [英] Using for loop variable outside of the for loop

查看:126
本文介绍了在for循环之外使用for循环变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这怎么可能?在这里,我将i的值用于for循环,而不是for循环.

I don't understand how this is possible? Here I am using the value of i for the for loop, outside the for loop.

for i, kv in enumerate(bucket): 
    k, v = kv  
    if key == k:
        key_exists = True
        break 

#here is the issue...

if key_exists:
    bucket[i] = ((key, value))
    print(i)
else:
    bucket.append((key, value))

推荐答案

这是可能的,因为Python没有块作用域.在for循环中分配的变量(在您的代码中为i)并不具有仅限于for循环的较窄范围.它存在于外部作用域中,因此在循环之后仍然可用.

This is possible because Python does not have block scope. The variable assigned to in the for loop (i in your code) doesn't have its own narrower scope limited to just the for loop; it exists in the outer scope, so it remains available after the loop.

例如:

for i in range(10):
    pass

print(i) # prints 9

循环内的任何其他分配也是如此.出于相同的原因,在这里,变量j在循环之后是可见的:for循环块不是单独的,更狭窄的范围.

The same is true of any other assignment inside the loop. Here, the variable j is visible after the loop, for the same reason: the for loop block is not a separate, narrower scope.

for i in range(10):
    j = 17

print(j) # prints 17

这篇关于在for循环之外使用for循环变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆