擅长:python、mysql、java
<p>在python2.x上,<code>dict.keys</code>或多或少毫无价值。您可以直接迭代字典的键:</p>
<pre><code>for key in d:
...
</code></pre>
<p>这将比迭代键更有效:</p>
^{2}$
<p>这就形成了一个单独的列表,然后<em>然后</em>有效地对其进行迭代两次+一堆额外的内存开销,比如一个丢弃的列表,等等</p>
<hr/>
<p>您的用例实际上是在对键进行成员资格测试。区别在于:</p>
<pre><code>x in some_list # is "x" an item in the list?
</code></pre>
<p>以及</p>
<pre><code>x in some_dict # is "x" a key in the dictionary?
</code></pre>
<p>对<code>list</code>对象的成员资格测试是O(N),而对<code>dict</code>的成员资格测试是O(1)。因此,对于循环的每一个“回合”,您都要执行一个O(N)list构造和一个O(N)查找,以查看该项是否在列表中,而不是对键进行简单的O(1)哈希查找。在</p>
<p>值得注意的是,如果你真的需要一个字典的键列表,你可以很容易地得到它</p>
<pre><code>list(d)
</code></pre>
<hr/>
<p>幸运的是,python3.x已经朝着正确的方向迈出了一步。<code>d.keys()</code>在python3.x中返回一个类似于<code>set</code>的对象。您可以使用它来高效地计算两个字典的键的交集,例如,这在某些情况下是有用的。在</p>
<p>同样值得指出的是,与<code>list</code>的O(n)成员身份测试相比,python3.x中的<code>set</code>类对象(称为<code>dict_keys</code>对象)也具有O(1)成员身份测试(这是对看起来像<code>set</code>的对象的预期)。在</p>
<p>因此,在python2.x<em>和</em>python3.x中,这是一件很好的事情,当您试图编写与以下任何一种兼容的代码时,请记住这一点</p>