<p>是的,在那里读很好。这是因为当你在内部创建一个<code>for</code>循环时,它有一个机制来为你创建<code>indexer</code>(在你的例子中是<code>i</code>),然后通过每次给它分配新的值来逐个增加它。因此,可以在<code>for</code>循环之后使用<code>i</code>。因此,在:</p>
<pre><code>a=[1,2,3,4,5]
for i in range(len(a)):
if a[i] == 2:
break
</code></pre>
<p><code>i</code>并没有被真正删除。要删除<code>i</code>,可以使用<code>del</code>关键字:</p>
<pre><code>a=[1,2,3,4,5]
for i in range(len(a)):
if a[i] == 2:
break
del i #deleted here
print i # now this will give you error!
</code></pre>
<p>如果要替换,只需重新定义:</p>
<pre><code>a=[1,2,3,4,5]
for i in range(len(a)):
if a[i] == 2:
break
i = [] #now this is a list, not an integer anymore
print i # now this will give you different result: []
</code></pre>
<p>类似地,例如,如果在if块中创建列表:</p>
<pre><code>if i == 0: #suppose you really enter this block
a = [] #a is created here
a.append(b) #but a can be used here, assuming the previous if is really entered
</code></pre>
<p>这就是Python的工作原理。你知道吗</p>
<p>部分相关岗位:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/35618307/how-to-transform-string-into-dict/35618686#35618686">How to transform string into dict</a></li>
<li><a href="https://stackoverflow.com/questions/35768738/for-loop-behaviour-in-python?lq=1">'For' loop behaviour in Python</a></li>
</ul>