擅长:python、mysql、java
<p>的确,你是对的。这在<a href="http://docs.python.org/reference/expressions.html#list-displays">Expressions section in the Python Language Reference</a>中有详细描述。</p>
<p>特别要注意在一个列表理解中几个<code>for</code>的嵌套顺序,总是从左到右:</p>
<pre><code>>>> matrix = [[1, 2], [3, 4]]
>>> [item for item in row for row in matrix] # oops!
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
[item for item in row for row in matrix]
NameError: name 'row' is not defined
>>> [item for row in matrix for item in row] # nesting is in left-to-right order
[1, 2, 3, 4]
</code></pre>