<p>您可以使用列表:</p>
<pre><code>In [64]: matrix = [["username", "name", "password"],["username2","name2","password2"]]
In [65]: matrix
Out[65]: [['username', 'name', 'password'], ['username2', 'name2', 'password2']]
</code></pre>
<p>访问第一行(因为Python使用基于0的索引):</p>
<pre><code>In [66]: matrix[0]
Out[66]: ['username', 'name', 'password']
</code></pre>
<p>访问第一行中的第二项:</p>
<pre><code>In [67]: matrix[0][1]
Out[67]: 'name'
</code></pre>
<hr/>
<p>列表不是数据结构的好选择
如果要根据用户名查找名称。
要做到这一点,您必须(潜在地)遍历<code>matrix</code>中的所有项
查找其用户名与指定用户名匹配的项。
完成搜索的时间将随着矩阵中的行数线性增长。</p>
<p>相比之下,不管有多少,dict的平均值都是<a href="http://wiki.python.org/moin/TimeComplexity" rel="nofollow">constant-time lookups</a>
键在dict中。例如,如果要定义</p>
<pre><code>matrix = {
'capitano': {'name':'Othello', 'password':'desi123'}
'thewife': {'name':'Desdemona', 'password':'3apples'}
}
</code></pre>
<p>(其中<code>'capitano'</code>和<code>'thewife'</code>是用户名)</p>
<p>然后要查找用户名为<code>'capitano'</code>的人的姓名,可以使用</p>
<pre><code>matrix['capitano']['name']
</code></pre>
<p>Python将返回<code>'Othello'</code>。</p>
<hr/>
<p>函数是Python中的一级对象:您可以将它们作为对象传递,就像传递数字或字符串一样。因此,例如,可以将函数存储为dict(key,value)对中的值:</p>
<pre><code>from __future__ import print_function
matrix = {'hello': {'action': lambda: print('hello')} }
</code></pre>
<p>然后调用函数(注意括号):</p>
<pre><code>matrix['hello']['action']()
# hello
</code></pre>