擅长:python、mysql、java
<p><code>defaultdict</code>将为丢失的每个键调用工厂函数。如果您在<code>sum()</code>中使用它,其中有许多键丢失,那么您确实会创建一大堆字典,这些字典会增长到包含更多键而不使用它们。你知道吗</p>
<p>切换到此处使用<a href="https://docs.python.org/2/library/stdtypes.html#dict.get" rel="nofollow">^{<cd3>} method</a>以防止创建对象:</p>
<pre><code>positive_assoc = sum(pmi.get(term, {}).get(tx, 0) for tx in positive_vocab)
negative_assoc = sum(pmi.get(term, {}).get(tx, 0) for tx in negative_vocab)
</code></pre>
<p>注意,<code>pmi.get()</code>调用返回一个空字典,因此链式的<code>dict.get()</code>调用继续工作,如果没有与给定的<code>term</code>关联的字典,则可以返回默认的<code>0</code>。你知道吗</p>