擅长:python、mysql、java
<p>从技术上讲,您试图为未初始化的数组编制索引。在添加项之前,必须首先用列表初始化外部列表;Python调用
“列表理解”。</p>
<pre><code># Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5;
Matrix = [[0 for x in range(w)] for y in range(h)]
</code></pre>
<h2>现在可以向列表中添加项:</h2>
<pre><code>Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid
</code></pre>
<p>注意,矩阵是“y”主地址,换句话说,“y索引”在“x索引”之前。</p>
<pre><code>print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!
</code></pre>
<p>尽管您可以随意命名它们,但我这样看是为了避免索引时可能出现的一些混乱,如果您对内部和外部列表都使用“x”,并且希望使用非正方形矩阵。</p>