<p>从<a href="http://effbot.org/zone/python-for-statement.htm" rel="nofollow noreferrer">Understanding Python's "for" statement</a>:</p>
<blockquote>
<p>And in its simplest and original form, this is exactly what the for-in statement does; when you write</p>
</blockquote>
<pre><code>for name in train:
do something with name
</code></pre>
<blockquote>
<p>the interpreter will simply fetch <code>train[0]</code>and assign it to <code>name</code>, and then execute the code block. It’ll then
fetch <code>train[1]</code>, <code>train[2]</code>, and so on, until it gets an <code>IndexError</code>.</p>
</blockquote>
<hr/>
<p>或者,我们可以使用<a href="https://docs.python.org/2/library/dis.html#module-dis" rel="nofollow noreferrer">^{<cd1>}</a>并检查机器代码:</p>
<pre><code>>>> def forloop():
for i in range(1, 10):
print i
>>> dis.dis(forloop)
2 0 SETUP_LOOP 28 (to 31)
3 LOAD_GLOBAL 0 (range)
6 LOAD_CONST 1 (1)
9 LOAD_CONST 2 (10)
12 CALL_FUNCTION 2
15 GET_ITER
>> 16 FOR_ITER 11 (to 30)
19 STORE_FAST 0 (i)
3 22 LOAD_FAST 0 (i)
25 PRINT_ITEM
26 PRINT_NEWLINE
27 JUMP_ABSOLUTE 16
>> 30 POP_BLOCK
>> 31 LOAD_CONST 0 (None)
34 RETURN_VALUE
</code></pre>
<p>我们设置一个循环,呼叫范围,然后:</p>
<p><code>16</code><a href="https://docs.python.org/2/library/dis.html#opcode-FOR_ITER" rel="nofollow noreferrer">^{<cd3>}</a><code>11 (to 30)</code></p>
<p>它将迭代器的<em>结果</em>推送到堆栈上,然后我们将其<code>STORE_FAST</code>作为<code>i</code>使用。你知道吗</p>
<p>当迭代器完成时,<code>FOR_ITER</code>“<code>TOS</code>弹出[迭代器],字节码计数器按增量递增。<code>dis</code>显示的是30:<code>POP_BLOCK</code>,结束for循环。你知道吗</p>
<p>这与开头描述的过程一致。你知道吗</p>